﻿using Coldairarrow.Entity.Base;
using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.DingReving;
using Coldairarrow.Entity.DTO;
using Coldairarrow.Entity.IT;
using Coldairarrow.Entity.PB;
using Coldairarrow.Entity.TD;
using Coldairarrow.IBusiness;
using Coldairarrow.IBusiness.DTO;
using Coldairarrow.Util;
using EFCore.Sharding;
using LinqKit;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace Coldairarrow.Business.PB
{
    public partial class PB_TransportBillBusiness : BaseBusiness<PB_TransportBill>, IPB_TransportBillBusiness, ITransientDependency
    {
        readonly IOperator _operator;
        readonly IOperatorDept _opdept;

        public PB_TransportBillBusiness(IDbAccessor db, IOperator @operator, IOperatorDept @opdept)
            : base(db)
        {
            _operator = @operator;
            _opdept = @opdept;

        }

        #region 外部接口

        public async Task<PageResult<PB_TransportBillDTO>> GetDataListAsync(PageInput<BilldConditionDTO> input)
        {
            var search = input.Search;
            Expression<Func<PB_TransportBill, PB_Vehicle, PB_DeliveryNotice, Base_EnumItem, PB_TransportBillDTO>> select = (a, b, c, d) => new PB_TransportBillDTO { PlateNO = b.PlateNO, SupplierId = b.SupplierId, Abstract = c.Abstract, IssueDate = c.IssueDate, TransportType = d.Name };
            select = select.BuildExtendSelectExpre();
            var q = from a in GetIQueryable().AsExpandable()
                    join b in Db.GetIQueryable<PB_Vehicle>() on a.Vehicle equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    join c in Db.GetIQueryable<PB_DeliveryNotice>() on a.DeliveryNoticeId equals c.Id into ac
                    from c in ac.DefaultIfEmpty()
                    join d in Db.GetIQueryable<Base_EnumItem>() on a.BillType equals d.Code into ad
                    from d in ad.Where(u => u.EnumCode.Contains("TransportType")).DefaultIfEmpty()
                    select @select.Invoke(a, b, c, d);


            //筛选
            if (!search.Keyword.IsNullOrEmpty())
            {
                var keyword = $"%{search.Keyword}%";
                q = q.Where(x =>
                      EF.Functions.Like(x.Id, keyword)
                      || EF.Functions.Like(x.DeliveryNoticeId, keyword)
                      || EF.Functions.Like(x.PlateNO, keyword));
            }
            if (!search.BillType.IsNullOrEmpty())
            {
                q = q.Where(x => x.BillType == search.BillType);
            }
            //获取登录人的部门信息
            var deptdata = await _opdept.GetOperatorDeptType();
            if (deptdata.DeptType == 8)
            {
                string sqlMain = @"select b.ParentId as BillId from PB_Purchase as a join PB_TransportBillGroup as b on a.Id=b.DeliveryNoticeId where a.SupplierId='" + deptdata.SupplierId + "' group by b.ParentId";
                List<PurchaseBillGroupDTO> listdata = await Db.GetListBySqlAsync<PurchaseBillGroupDTO>(sqlMain);
                List<string> liststr = new List<string>();
                foreach (var item in listdata)
                {
                    liststr.Add(item.BillId);
                }
                q = q.Where(x => liststr.Contains(x.Id));
            }
            else
            {
                q = q.Where(d => _operator.Property.DeptIds.Contains(d.DeptId));
            }
            if (!input.Search.ProjectName.IsNullOrEmpty())
            {
                List<String> ListStr = new List<string>();
                string sql = " SELECT  Bill.ID 'Id' FROM PB_TransportBillGroup AS Grouprs  LEFT JOIN PB_TransportBill AS Bill ON Grouprs.ParentId = Bill.Id   LEFT JOIN PB_DeliveryNotice AS Notice ON Grouprs.DeliveryNoticeId = Notice.Id  LEFT JOIN PB_TransportBillDetail AS detail ON detail.ParentId = Bill.Id   LEFT JOIN PB_PickUpList AS PickList ON detail.PreparationNoteId = PickList.Id  LEFT JOIN PB_PickUpMain AS Main ON PickList.ParentId = Main.Id LEFT JOIN PB_DeliveryNoticeItem AS Item ON Main.ParentId = Item.Id  AND Item.ParentId = Notice.id   LEFT JOIN PB_Project AS Project ON Notice.ProjectId = Project.Id  LEFT JOIN PB_TransportBillDetailList AS detaillist ON detaillist.BillDetailId = detail.Id  AND detaillist.ProjectId = Notice.ProjectId  LEFT JOIN PB_Vehicle AS Vehicle ON Bill.Vehicle = Vehicle.Id WHERE Project.`Name` LIKE '%" + input.Search.ProjectName + "%'";
                List<PB_TransportBill> dbs = await Db.GetListBySqlAsync<PB_TransportBill>(sql.ToString());
                foreach (var item in dbs)
                {
                    ListStr.Add(item.Id);
                }
                q = q.Where(m => ListStr.Contains(m.Id));
            }
            return await q.GetPageResultAsync(input);
        }

        public async Task<PageResult<PB_TransportBillDTO>> GetBilDataListAsync(PageInput<ConditionDTO> input)
        {
            var where = LinqHelper.True<PB_TransportBillDTO>();
            var search = input.Search;
            Expression<Func<PB_TransportBill, PB_Vehicle, PB_DeliveryNotice, Base_EnumItem, PB_TransportBillDTO>> select = (a, b, c, d) => new PB_TransportBillDTO { PlateNO = b.PlateNO, SupplierId = b.SupplierId, Abstract = c.Abstract, IssueDate = c.IssueDate, TransportType = d.Name };
            select = select.BuildExtendSelectExpre();
            var q = from a in GetIQueryable().AsExpandable()
                    join b in Db.GetIQueryable<PB_Vehicle>() on a.Vehicle equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    join c in Db.GetIQueryable<PB_DeliveryNotice>() on a.DeliveryNoticeId equals c.Id into ac
                    from c in ac.DefaultIfEmpty()
                    join d in Db.GetIQueryable<Base_EnumItem>() on a.BillType equals d.Code into ad
                    from d in ad.Where(u => u.EnumCode.Contains("TransportType")).DefaultIfEmpty()
                    select @select.Invoke(a, b, c, d);
            //筛选
            if (!search.Keyword.IsNullOrEmpty())
            {
                if (search.Condition == "State")
                {
                    q = q.Where(x => x.State == search.Keyword.ToInt());
                    return await q.GetPageResultAsync(input);
                }
                else
                {
                    var keyword = $"%{search.Keyword}%";
                    q = q.Where(x => EF.Functions.Like(x.PlateNO, keyword) || EF.Functions.Like(x.DriverName, keyword) || EF.Functions.Like(x.Abstract, keyword));

                }
            }
            where = where.And(d => _operator.Property.DeptIds.Contains(d.DeptId));
            return await q.Where(where).GetPageResultAsync(input);
        }

        public async Task<PageResult<PB_TransportBillDTO>> GetBilVehicleWeighingAsync(PageInput<BilldConditionDTO> input)
        {
            var where = LinqHelper.True<PB_TransportBillDTO>();
            var search = input.Search;
            Expression<Func<PB_TransportBill, PB_Vehicle, PB_DeliveryNotice, Base_EnumItem, Base_User, PB_TransportBillDTO>> select = (a, b, c, d, e) => new PB_TransportBillDTO { PlateNO = b.PlateNO, SupplierId = b.SupplierId, Abstract = c.Abstract, IssueDate = c.IssueDate, TransportType = d.Name, WeighingPeopled = e.RealName };
            select = select.BuildExtendSelectExpre();
            var q = from a in GetIQueryable().AsExpandable()
                    join b in Db.GetIQueryable<PB_Vehicle>() on a.Vehicle equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    join c in Db.GetIQueryable<PB_DeliveryNotice>() on a.DeliveryNoticeId equals c.Id into ac
                    from c in ac.DefaultIfEmpty()
                    join d in Db.GetIQueryable<Base_EnumItem>() on a.BillType equals d.Code into ad
                    from d in ad.Where(u => u.EnumCode.Contains("TransportType")).DefaultIfEmpty()
                    join e in Db.GetIQueryable<Base_User>() on a.WeighingPeople equals e.UserName into ae
                    from e in ae.DefaultIfEmpty()
                    select @select.Invoke(a, b, c, d, e);
            //筛选
            if (!search.Keyword.IsNullOrEmpty())
            {
                var keyword = $"%{search.Keyword}%";
                q = q.Where(x =>
                   EF.Functions.Like(x.PlateNO, keyword)
                || EF.Functions.Like(x.DriverName, keyword)
                || EF.Functions.Like(x.Iphone, keyword));
            }
            if (!search.BillType.IsNullOrEmpty())
            {
                q = q.Where(x => x.BillType == search.BillType);
            }
            //获取所有的部门信息
            List<string> liststr = await _opdept.GetDeptString();
            q = q.Where(x => liststr.Contains(x.DeptId));
            //q = q.Where(x => x.State == 1 || x.State == 2 || x.State == 3);
            return await q.Where(where).GetPageResultAsync(input);
        }


        public async Task<List<RelevantCodeDTO>> GetRelevantCodeDataListAsync(PageInput<RelevantCodeConditionDTO> input)
        {
            string type = input.Search.BillType;
            List<RelevantCodeDTO> relevantCodeDTOList = new List<RelevantCodeDTO>();
            switch (type)
            {
                case "Delivery":
                    List<PB_DeliveryNotice> pB_DeliveryNotices = await Db.GetListAsync<PB_DeliveryNotice>();
                    if (!input.Search.Type.IsNullOrEmpty() && !input.Search.Keyword.IsNullOrEmpty())
                    {
                        pB_DeliveryNotices = pB_DeliveryNotices.Where(u => u.Id.Contains(input.Search.Keyword) || (!u.Abstract.IsNullOrEmpty() && u.Abstract.Contains(input.Search.Keyword)) && u.AuditStatus == 1).ToList();
                    }
                    foreach (var item in pB_DeliveryNotices.OrderByDescending(u => u.CreateTime))
                    {
                        // if (item.AuditStatus == 1)
                        // {
                        RelevantCodeDTO relevantCodeDTO = new RelevantCodeDTO();
                        relevantCodeDTO.Id = item.Id;
                        relevantCodeDTO.BillNo = item.Id;
                        relevantCodeDTO.Name = item.Abstract;
                        relevantCodeDTOList.Add(relevantCodeDTO);
                        // }
                    }
                    break;
                case "Return":
                    List<PB_DeliveryNotice> pB_Return = await Db.GetListAsync<PB_DeliveryNotice>();
                    if (!input.Search.Type.IsNullOrEmpty() && !input.Search.Keyword.IsNullOrEmpty())
                    {
                        pB_Return = pB_Return.Where(u => u.Id.Contains(input.Search.Keyword) || (!u.Abstract.IsNullOrEmpty() && u.Abstract.Contains(input.Search.Keyword))).ToList();
                    }
                    pB_Return = pB_Return.Where(m => m.Type == 2).ToList();
                    foreach (var item in pB_Return.OrderByDescending(u => u.CreateTime))
                    {
                        //if (item.State == 0)
                        //{
                        RelevantCodeDTO relevantCodeDTO = new RelevantCodeDTO();
                        relevantCodeDTO.Id = item.Id;
                        relevantCodeDTO.BillNo = item.Id;
                        relevantCodeDTO.Name = item.Abstract;
                        relevantCodeDTOList.Add(relevantCodeDTO);
                        //}
                    }
                    break;
                case "Outsourcing_O":
                    Expression<Func<PB_OutsourcingBill, PB_Supplier, PB_OutsourcingBillViewDTO>> select = (a, b) => new PB_OutsourcingBillViewDTO
                    {
                        SupplierName = b.Name
                    };
                    select = select.BuildExtendSelectExpre();
                    var q = from a in Db.GetIQueryable<PB_OutsourcingBill>().AsExpandable()
                            join b in Db.GetIQueryable<PB_Supplier>() on a.OutsourcingCompanyId equals b.Id into ab
                            from b in ab.DefaultIfEmpty()
                            select @select.Invoke(a, b);
                    //List<PB_OutsourcingBill> pB_OutsourcingBills = await Db.GetListAsync<PB_OutsourcingBill>();
                    //获取已经可以开始装车的外协单
                    q = q.Where(u => u.Status == 1 || u.Status == 2);
                    if (!input.Search.Keyword.IsNullOrEmpty())
                    {
                        q = q.Where(u => u.Id.Contains(input.Search.Keyword) || u.SupplierName.Contains(input.Search.Keyword) || u.OutName.Contains(input.Search.Keyword));
                    }
                    foreach (var item in q.OrderByDescending(u => u.CreateTime))
                    {
                        //if (item.State == 0)
                        //{
                        RelevantCodeDTO relevantCodeDTO = new RelevantCodeDTO();
                        relevantCodeDTO.Id = item.Id;
                        relevantCodeDTO.BillNo = item.BillCode;
                        relevantCodeDTO.SupplierName = item.SupplierName;
                        relevantCodeDTO.Name = item.OutName;
                        relevantCodeDTO.TotalWeight = item.TheoreticalWT;
                        relevantCodeDTOList.Add(relevantCodeDTO);
                        //}
                    }
                    break;
                case "Outsourcing_I":
                    Expression<Func<PB_OutsourcingBill, PB_Supplier, PB_OutsourcingBillViewDTO>> selects = (a, b) => new PB_OutsourcingBillViewDTO
                    {
                        SupplierName = b.Name
                    };
                    selects = selects.BuildExtendSelectExpre();
                    var w = from a in Db.GetIQueryable<PB_OutsourcingBill>().AsExpandable()
                            join b in Db.GetIQueryable<PB_Supplier>() on a.OutsourcingCompanyId equals b.Id into ab
                            from b in ab.DefaultIfEmpty()
                            select @selects.Invoke(a, b);
                    //List<PB_OutsourcingBill> pB_OutsourcingBills = await Db.GetListAsync<PB_OutsourcingBill>();
                    w = w.Where(u => u.Status == 4);
                    if (!input.Search.Keyword.IsNullOrEmpty())
                    {
                        w = w.Where(u => u.Id.Contains(input.Search.Keyword) || u.SupplierName.Contains(input.Search.Keyword) || u.OutName.Contains(input.Search.Keyword));
                    }
                    foreach (var item in w.OrderByDescending(u => u.CreateTime))
                    {
                        //if (item.State == 0)
                        //{
                        RelevantCodeDTO relevantCodeDTO = new RelevantCodeDTO();
                        relevantCodeDTO.Id = item.Id;
                        relevantCodeDTO.BillNo = item.BillCode;
                        relevantCodeDTO.SupplierName = item.SupplierName;
                        relevantCodeDTO.Name = item.OutName;
                        relevantCodeDTOList.Add(relevantCodeDTO);
                        //}
                    }
                    break;
                default:
                    break;
            }
            return relevantCodeDTOList;
        }
        public async Task<PB_TransportBill> GetTheDataAsync(string id)
        {
            /*
             * 开发人：崔楠
             * 提交日期：2022-02-23 15:00
             * 修改内容：货运派车单多通知单返回单个实体
             * 上传SVN：是
             */
            var _DeliveryNoticeIds = await Db.GetIQueryable<PB_TransportBillGroup>().Where(s => s.ParentId == id).ToListAsync();
            var bill = await GetEntityAsync(id);
            bill.DeliveryNoticeId = String.Join(",", _DeliveryNoticeIds);
            return bill;
        }

        public async Task<PB_TransportBillDTO> GetTheDataAndPB_Vehicle(string id)
        {
            /*
             * 开发人：崔楠
             * 提交日期：2022-02-23 15:00
             * 修改内容：货运派车单多通知单返回单个实体
             * 上传SVN：是
             */
            Expression<Func<PB_TransportBill, PB_Vehicle, PB_DeliveryNotice, PB_TransportBillDTO>> select = (a, b, c) => new PB_TransportBillDTO { PlateNO = b.PlateNO, SupplierId = b.SupplierId, Abstract = c.Abstract, IssueDate = c.IssueDate };
            select = select.BuildExtendSelectExpre();
            var q = from a in GetIQueryable().AsExpandable()
                    join b in Db.GetIQueryable<PB_Vehicle>() on a.Vehicle equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    join c in Db.GetIQueryable<PB_DeliveryNotice>() on a.DeliveryNoticeId equals c.Id into ac
                    from c in ac.DefaultIfEmpty()
                    select @select.Invoke(a, b, c);
            var entity = await q.FirstOrDefaultAsync(c => c.Id == id);
            var _DeliveryNoticeIds = await Db.GetIQueryable<PB_TransportBillGroup>().Where(s => s.ParentId == id).ToListAsync();
            if (_DeliveryNoticeIds.Count > 0)
            {
                string _ids = "";
                foreach (var item in _DeliveryNoticeIds)
                {
                    _ids += item.DeliveryNoticeId + ",";
                }
                entity.DeliveryNoticeId = _ids.Substring(0, _ids.Length - 1);
            }

            return entity;
        }

        public async Task AddDataAsync(PB_TransportBill data)
        {

            string[] DeliveryNoticeIds = data.DeliveryNoticeId.Split(',');
            if (data.BillType == "Return")
            {
                await ExecuteSqlAsync(" UPDATE PB_Return SET BillId='" + data.Id + "' WHERE Id in (" + data.DeliveryNoticeId + ")");
            }
            //插入PB_TransportBill主表
            if (data.BillType == "Purchase")
            {
                List<string> liststr = new List<string>();
                foreach (var item in DeliveryNoticeIds)
                {
                    liststr.Add(item);
                }
                List<PB_Purchase> Purchaselist = await Db.GetIQueryable<PB_Purchase>().Where(x => liststr.Contains(x.Id)).ToListAsync();
                var deptdata = Purchaselist.GroupBy(x => new { x.DeptId }).Select(x => new { DeptId = x.Key.DeptId }).FirstOrDefault();
                data.DeptId = deptdata.DeptId;
            }
            else
            {
                data.DeptId = _operator?.Property.DepartmentId;
            }

            data.QrCode = h_Bill + "," + data.Id;
            //如果是外协回货
            if (data.BillType != "Outsourcing_I")
            {
                data.DeliveryNoticeId = "";//此列弃用，改存子表PB_TransportBillGroup
            }
            data.InventoryErrStatus = false;
            data.StockUpErrStatus = false;
            data.WeightErrStatus = false;
            data.ReturnStatus = 0;
            await InsertAsync(data);
            //插入关联发货单子表PB_TransportBillGroup
            if (DeliveryNoticeIds.Length > 0)
            {
                //先删除已经存在的子表数据
                await ExecuteSqlAsync(" DELETE FROM PB_TransportBillGroup WHERE ParentId ='" + data.Id + "'");
                List<PB_TransportBillGroup> _PB_TransportBillGroups = new List<PB_TransportBillGroup>();
                foreach (var item in DeliveryNoticeIds)
                {
                    PB_TransportBillGroup _PB_TransportBillGroup = new PB_TransportBillGroup()
                    {
                        Id = IdHelper.GetId(),
                        CreateTime = DateTime.Now,
                        CreatorId = _operator.UserId,
                        ParentId = data.Id,
                        DeliveryNoticeId = item,
                        Deleted = false
                    };
                    _PB_TransportBillGroups.Add(_PB_TransportBillGroup);
                }
                await Db.InsertAsync<PB_TransportBillGroup>(_PB_TransportBillGroups);
            }

        }


        public async Task UpdateDataAsync(PB_TransportBill data)
        {
            PB_TransportBill data1 = await Db.GetIQueryable<PB_TransportBill>().Where(s => s.Id == data.Id).FirstOrDefaultAsync();

            //派车信息为外协发离厂更改外包单的状态
            if (data.BillType == "Outsourcing_O")
            {
                List<PB_TransportBillDetail> TransportBillDetail = await Db.GetIQueryable<PB_TransportBillDetail>().Where(x => x.ParentId == data.Id).ToListAsync();
                var outbilldata = TransportBillDetail.GroupBy(x => new { x.PreparationNoteId }).Select(x => new { OutBillId = x.Key.PreparationNoteId }).ToList();
                List<string> OutBillIds = new List<string>();
                foreach (var item in outbilldata)
                {
                    OutBillIds.Add(item.OutBillId);
                }
                await ExecuteSqlAsync(" update PB_OutsourcingBill set Status=4 where Id in ('" + string.Join("','", OutBillIds.ToArray()) + "'); ");
            }

            if (data.State == 1)
            {
                //如果是外协回则更改外包订单状态
                //if (data1.BillType == "Outsourcing_I")
                //{
                //    await ExecuteSqlAsync($" update PB_OutsourcingBill set Status = 7  where Id = {data1.DeliveryNoticeId} ;");
                //}
                data1.Id = data.Id;
                data1.State = data.State;
                data1.EnteringPlantMan = data.EnteringPlantMan;
                data1.IntoTime = data.IntoTime;
                data1.Remark = data.Remark;
                data1.WeighingPeople = "";
                data.QrCode = h_Bill + "," + data.Id;
                data1.BillType = data.BillType;//派车类型
                data1.DeliveryNoticeId = data.DeliveryNoticeId;//关联发货单
                data1.CarrierId = data.CarrierId; //承运商
                data1.Vehicle = data.Vehicle;//车牌
                data1.PlateNO = data.PlateNO; // 车牌号
                data1.TrainNumber = data.TrainNumber;//车次
                data1.DriverName = data.DriverName;//司机姓名
                data1.Iphone = data.Iphone;//手机号
                data1.VehicleLicense = data.VehicleLicense;//行驶证
                data1.DrivingLicense = data.DrivingLicense;//驾驶证
                data1.Tunnage = data.Tunnage;//载重
                data1.SendTime = data.SendTime;    //派车时间
                data1.AcceptanceRemarks = data.AcceptanceRemarks;
                if (data.EmptyNumber != data1.EmptyNumber)
                {
                    data1.EmptyNumber = data.EmptyNumber;
                    data1.EmptyTime = DateTime.Now;
                }
                data1.IntoTime = data.IntoTime;
                data1.DocumentMaker = data.DocumentMaker;
                if (data.RoughweightNumber != data1.RoughweightNumber)
                {
                    data1.RoughweightNumber = data.RoughweightNumber;
                    data1.RoughweightTime = DateTime.Now;
                }
                data1.WeighingPeople = data.WeighingPeople;
                if (!data1.EmptyNumber.IsNullOrEmpty() && !data1.RoughweightNumber.IsNullOrEmpty())
                {
                    data1.NetloadNumber = data1.RoughweightNumber - data1.EmptyNumber;
                }
                data1.CreateTime = data.CreateTime;
                data1.CreatorId = data.CreatorId;
                data1.Deleted = data.Deleted;
            }
            else
            {
                data1.State = data.State;
                data1.ExFactoryMan = data.ExFactoryMan;
                data1.DepartureTime = data.DepartureTime;
                //data1.EmptyNumber = data.EmptyNumber;
                //data1.RoughweightNumber = data.RoughweightNumber;
                //data1.EmptyTime = DateTime.Now;
                //data1.RoughweightTime = DateTime.Now;
                data1.BillType = data.BillType;//派车类型
                data1.DeliveryNoticeId = data.DeliveryNoticeId;//关联发货单
                data1.CarrierId = data.CarrierId; //承运商
                data1.Vehicle = data.Vehicle;//车牌
                data1.PlateNO = data.PlateNO; // 车牌号
                data1.TrainNumber = data.TrainNumber;//车次
                data1.DriverName = data.DriverName;//司机姓名
                data1.Iphone = data.Iphone;//手机号
                data1.VehicleLicense = data.VehicleLicense;//行驶证
                data1.DrivingLicense = data.DrivingLicense;//驾驶证
                data1.Tunnage = data.Tunnage;//载重
                data1.SendTime = data.SendTime;    //派车时间
                data1.AcceptanceRemarks = data.AcceptanceRemarks;
                if (data.EmptyNumber == null)
                {
                    throw new BusException("车辆未进行皮重过磅");
                }

                if (data.EmptyNumber != data1.EmptyNumber && !data.EmptyNumber.IsNullOrEmpty())
                {
                    data1.EmptyNumber = data.EmptyNumber;
                    data1.EmptyTime = DateTime.Now;
                }
                if (data.RoughweightNumber == null)
                {
                    throw new BusException("车辆未进行毛重过磅");
                }
                if (data.RoughweightNumber != data1.RoughweightNumber && !data.RoughweightNumber.IsNullOrEmpty())
                {
                    data1.RoughweightNumber = data.RoughweightNumber;
                    data1.RoughweightTime = DateTime.Now;
                }
                data1.WeighingPeople = data.WeighingPeople;
                if (!data1.EmptyNumber.IsNullOrEmpty() && !data1.RoughweightNumber.IsNullOrEmpty())
                {
                    data1.NetloadNumber = data1.RoughweightNumber - data1.EmptyNumber;
                }
            }
            List<string> props = GetFieldList(data1);
            if (props.IsNullOrEmpty())
            {
                await UpdateAsync(data1);
            }
            else
            {
                await UpdateAsync(data1, props);
            }
            //更新关联发货单子表PB_TransportBillGroup
            string[] DeliveryNoticeIds = data.DeliveryNoticeId.Split(',');
            if (DeliveryNoticeIds.Length > 0)
            {
                //先删除已经存在的子表数据
                await ExecuteSqlAsync(" DELETE FROM PB_TransportBillGroup WHERE ParentId ='" + data.Id + "'");
                List<PB_TransportBillGroup> _PB_TransportBillGroups = new List<PB_TransportBillGroup>();
                foreach (var item in DeliveryNoticeIds)
                {
                    PB_TransportBillGroup _PB_TransportBillGroup = new PB_TransportBillGroup()
                    {
                        Id = IdHelper.GetId(),
                        CreateTime = DateTime.Now,
                        CreatorId = _operator.UserId,
                        ParentId = data.Id,
                        DeliveryNoticeId = item,
                        Deleted = false
                    };
                    _PB_TransportBillGroups.Add(_PB_TransportBillGroup);
                }
                await Db.InsertAsync<PB_TransportBillGroup>(_PB_TransportBillGroups);
            }
        }
        public async Task UpdateDataAsyncs(PB_TransportBill data)
        {
            PB_TransportBill data1 = await Db.GetIQueryable<PB_TransportBill>().Where(s => s.Id == data.Id).FirstOrDefaultAsync();


            if (data.State == 1)
            {
                //如果是外协回则更改外包订单状态
                if (data1.BillType == "Outsourcing_I")
                {
                    await ExecuteSqlAsync($" update PB_OutsourcingBill set Status = 7  where Id = {data1.DeliveryNoticeId} ;");
                }
                data1.Id = data.Id;
                data1.State = data.State;
                data1.EnteringPlantMan = data.EnteringPlantMan;
                data1.IntoTime = data.IntoTime;
                data1.Remark = data.Remark;
                data1.WeighingPeople = "";
                data.QrCode = h_Bill + "," + data.Id;
                data1.BillType = data.BillType;//派车类型
                data1.DeliveryNoticeId = data.DeliveryNoticeId;//关联发货单
                data1.CarrierId = data.CarrierId; //承运商
                data1.Vehicle = data.Vehicle;//车牌
                data1.PlateNO = data.PlateNO; // 车牌号
                data1.TrainNumber = data.TrainNumber;//车次
                data1.DriverName = data.DriverName;//司机姓名
                data1.Iphone = data.Iphone;//手机号
                data1.VehicleLicense = data.VehicleLicense;//行驶证
                data1.DrivingLicense = data.DrivingLicense;//驾驶证
                data1.Tunnage = data.Tunnage;//载重
                data1.SendTime = data.SendTime;    //派车时间
                data1.AcceptanceRemarks = data.AcceptanceRemarks;
                if (data.EmptyNumber != data1.EmptyNumber)
                {
                    data1.EmptyNumber = data.EmptyNumber;
                    data1.EmptyTime = DateTime.Now;
                }
                data1.IntoTime = data.IntoTime;
                data1.DocumentMaker = data.DocumentMaker;
                if (data.RoughweightNumber != data1.RoughweightNumber)
                {
                    data1.RoughweightNumber = data.RoughweightNumber;
                    data1.RoughweightTime = DateTime.Now;
                }
                data1.WeighingPeople = data.WeighingPeople;
                if (!data1.EmptyNumber.IsNullOrEmpty() && !data1.RoughweightNumber.IsNullOrEmpty())
                {
                    data1.NetloadNumber = data1.RoughweightNumber - data1.EmptyNumber;
                }
                data1.CreateTime = data.CreateTime;
                data1.CreatorId = data.CreatorId;
                data1.Deleted = data.Deleted;
            }
            else
            {
                data1.State = data.State;
                data1.ExFactoryMan = data.ExFactoryMan;
                data1.DepartureTime = data.DepartureTime;
                //data1.EmptyNumber = data.EmptyNumber;
                //data1.RoughweightNumber = data.RoughweightNumber;
                //data1.EmptyTime = DateTime.Now;
                //data1.RoughweightTime = DateTime.Now;
                data1.BillType = data.BillType;//派车类型
                data1.DeliveryNoticeId = data.DeliveryNoticeId;//关联发货单
                data1.CarrierId = data.CarrierId; //承运商
                data1.Vehicle = data.Vehicle;//车牌
                data1.PlateNO = data.PlateNO; // 车牌号
                data1.TrainNumber = data.TrainNumber;//车次
                data1.DriverName = data.DriverName;//司机姓名
                data1.Iphone = data.Iphone;//手机号
                data1.VehicleLicense = data.VehicleLicense;//行驶证
                data1.DrivingLicense = data.DrivingLicense;//驾驶证
                data1.Tunnage = data.Tunnage;//载重
                data1.SendTime = data.SendTime;    //派车时间
                data1.AcceptanceRemarks = data.AcceptanceRemarks;


                if (data.EmptyNumber != data1.EmptyNumber && !data.EmptyNumber.IsNullOrEmpty())
                {
                    data1.EmptyNumber = data.EmptyNumber;
                    data1.EmptyTime = DateTime.Now;
                }

                if (data.RoughweightNumber != data1.RoughweightNumber && !data.RoughweightNumber.IsNullOrEmpty())
                {
                    data1.RoughweightNumber = data.RoughweightNumber;
                    data1.RoughweightTime = DateTime.Now;
                }
                data1.WeighingPeople = data.WeighingPeople;
                if (!data1.EmptyNumber.IsNullOrEmpty() && !data1.RoughweightNumber.IsNullOrEmpty())
                {
                    data1.NetloadNumber = data1.RoughweightNumber - data1.EmptyNumber;
                }
            }
            List<string> props = GetFieldList(data1);
            if (props.IsNullOrEmpty())
            {
                await UpdateAsync(data1);
            }
            else
            {
                await UpdateAsync(data1, props);
            }
            //更新关联发货单子表PB_TransportBillGroup
            string[] DeliveryNoticeIds = data.DeliveryNoticeId.Split(',');
            if (DeliveryNoticeIds.Length > 0)
            {
                //先删除已经存在的子表数据
                await ExecuteSqlAsync(" DELETE FROM PB_TransportBillGroup WHERE ParentId ='" + data.Id + "'");
                List<PB_TransportBillGroup> _PB_TransportBillGroups = new List<PB_TransportBillGroup>();
                foreach (var item in DeliveryNoticeIds)
                {
                    PB_TransportBillGroup _PB_TransportBillGroup = new PB_TransportBillGroup()
                    {
                        Id = IdHelper.GetId(),
                        CreateTime = DateTime.Now,
                        CreatorId = _operator.UserId,
                        ParentId = data.Id,
                        DeliveryNoticeId = item,
                        Deleted = false
                    };
                    _PB_TransportBillGroups.Add(_PB_TransportBillGroup);
                }
                await Db.InsertAsync<PB_TransportBillGroup>(_PB_TransportBillGroups);
            }
        }
        public async Task DeleteDataAsync(List<string> ids)
        {
            /*
             * 开发人：崔楠
             * 提交日期：2022-02-23 15:00
             * 修改内容：删除货运派车单通知单子表
             * 上传SVN：是
             */
            await DeleteAsync(ids);
            await ExecuteSqlAsync(" DELETE FROM PB_TransportBillGroup WHERE ParentId in (" + String.Join(",", ids.ToArray()) + ")");
        }

        /// <summary>
        /// 获取车辆信息
        /// </summary>
        /// <param name="deptId">登录人组织Id</param>
        /// <param name="BillType">车辆类型</param>
        /// 发货类型的车辆在进厂后PDA可以选择   2022-02-18  赵锦涛
        public async Task<List<PB_TransportBillVehicleDTO>> GetCarInformationAsync(string deptId, string BillType)
        {
            //var q = GetIQueryable();
            Expression<Func<PB_TransportBill, PB_Vehicle, PB_TransportBillVehicleDTO>> select = (a, b) => new PB_TransportBillVehicleDTO
            {
                PlateName = b.PlateNO
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in Db.GetIQueryable<PB_TransportBill>().AsExpandable()
                    join b in Db.GetIQueryable<PB_Vehicle>() on a.Vehicle equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    select @select.Invoke(a, b);

            if (!deptId.IsNullOrEmpty())
            {
                //获取登录人法人一级组织信息
                var dpdata = await _opdept.GetOperatorDept();
                List<string> liststr = new List<string>();
                liststr.Add(dpdata.DetpId);
                //获取所有的部门信息
                List<Base_Department> deptlist = await Db.GetIQueryable<Base_Department>().ToListAsync();
                var listdata = deptlist.Where(x => x.ParentId == dpdata.DetpId).ToList();
                foreach (var item in listdata)
                {
                    liststr.Add(item.Id);
                    GetDeptItem(item.Id, liststr, deptlist);
                }
                if (BillType.IsNullOrEmpty())
                {
                    BillType = "Delivery";
                    q = q.Where(x => liststr.Contains(x.DeptId) && (x.State == 1) && x.BillType == BillType);
                }
                else
                {
                    q = q.Where(x => liststr.Contains(x.DeptId) && (x.State == 0) && x.BillType == BillType);
                }

            }
            var res = await q.OrderByDescending(x => x.CreateTime).ToListAsync();
            if (res.Count > 0)
            {
                return res;
            }
            else
            {
                throw new BusException("暂无数据");
            }

        }
        /// <summary>
        /// 大屏显示当日发货的车辆动态信息
        /// </summary>
        /// <param name="toTodayDays">到今天的天数。-1表示昨天。默认为0</param>
        public async Task<List<PB_TransportBillVehicleStateDTO>> GetTodayCarInformationAsync(int toTodayDays = 0)
        {
            //var q = GetIQueryable();
            Expression<Func<PB_TransportBill, PB_Vehicle, PB_TransportBillVehicleStateDTO>> select = (a, b) => new PB_TransportBillVehicleStateDTO
            {
                PlateName = b.PlateNO,
                CarCaptain = b.CarCaptain,
                Tunnage = b.Tunnage,
                StateName = "进厂"
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in Db.GetIQueryable<PB_TransportBill>().AsExpandable()
                    join b in Db.GetIQueryable<PB_Vehicle>() on a.Vehicle equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    select @select.Invoke(a, b);
            DateTime today = DateTime.Now.AddDays(toTodayDays).Date;
            string BillType = "Delivery";

            q = q.Where(x => x.BillType == BillType && (x.IntoTime >= today || x.DepartureTime >= today));
            var res = await q.ToListAsync();
            if (res.Count > 0)
            {
                res.ForEach(aData =>
                {
                    if (aData.DepartureTime >= today)
                    {
                        aData.StateName = "出厂";
                    }
                });
            }
            return res;
        }
        /// <summary>
        /// 大屏显示七日发货数量
        /// </summary>
        /// <param name="toTodayDays">到今天的天数。-1表示昨天。默认为0</param>
        /// <returns></returns>
        public async Task<PB_TransportBill7DaySend> GetSevenDaysDeliveryAmount(int toTodayDays = 7)
        {
            PB_TransportBill7DaySend res = new PB_TransportBill7DaySend();
            #region 老牟代码
            //string strSQL = "SELECT IFNULL(SUM(d.PackNums),0) AS value FROM PB_TransportBillDetail d";
            //strSQL += " JOIN PB_TransportBill p ON d.ParentId = p.Id AND p.BillType='Delivery' AND TO_DAYS(NOW())-TO_DAYS(p.DepartureTime)=" + (7-toTodayDays).ToString();
            //var temp = Db.GetListBySql<PB_DeliveryPlanValue3DTO>(strSQL).FirstOrDefault().value;
            ////保留两位小数
            //temp = Convert.ToDouble(temp.ToString("#0.##"));
            //res.series[0].data.Add(temp);
            //strSQL = "SELECT IFNULL(SUM(d.PackNums),0) AS value FROM PB_TransportBillDetail d";
            //strSQL += " JOIN PB_TransportBill p ON d.ParentId = p.Id AND p.BillType='Delivery' AND TO_DAYS(NOW())-TO_DAYS(p.DepartureTime)="+(6-toTodayDays).ToString();
            //temp = Db.GetListBySql<PB_DeliveryPlanValue3DTO>(strSQL).FirstOrDefault().value;
            //temp = Convert.ToDouble(temp.ToString("#0.##"));
            //res.series[0].data.Add(temp);            
            //strSQL = "SELECT IFNULL(SUM(d.PackNums),0) AS value FROM PB_TransportBillDetail d";
            //strSQL += " JOIN PB_TransportBill p ON d.ParentId = p.Id AND p.BillType='Delivery' AND TO_DAYS(NOW())-TO_DAYS(p.DepartureTime)="+(5-toTodayDays).ToString();
            //temp = Db.GetListBySql<PB_DeliveryPlanValue3DTO>(strSQL).FirstOrDefault().value;
            //temp = Convert.ToDouble(temp.ToString("#0.##"));
            //res.series[0].data.Add(temp); 
            //strSQL = "SELECT IFNULL(SUM(d.PackNums),0) AS value FROM PB_TransportBillDetail d";
            //strSQL += " JOIN PB_TransportBill p ON d.ParentId = p.Id AND p.BillType='Delivery' AND TO_DAYS(NOW())-TO_DAYS(p.DepartureTime)="+(4-toTodayDays).ToString();
            //temp = Db.GetListBySql<PB_DeliveryPlanValue3DTO>(strSQL).FirstOrDefault().value;
            //temp = Convert.ToDouble(temp.ToString("#0.##"));
            //res.series[0].data.Add(temp); 
            //strSQL = "SELECT IFNULL(SUM(d.PackNums),0) AS value FROM PB_TransportBillDetail d";
            //strSQL += " JOIN PB_TransportBill p ON d.ParentId = p.Id AND p.BillType='Delivery' AND TO_DAYS(NOW())-TO_DAYS(p.DepartureTime)="+(3-toTodayDays).ToString();
            //temp = Db.GetListBySql<PB_DeliveryPlanValue3DTO>(strSQL).FirstOrDefault().value;
            //temp = Convert.ToDouble(temp.ToString("#0.##"));
            //res.series[0].data.Add(temp); 
            //strSQL = "SELECT IFNULL(SUM(d.PackNums),0) AS value FROM PB_TransportBillDetail d";
            //strSQL += " JOIN PB_TransportBill p ON d.ParentId = p.Id AND p.BillType='Delivery' AND TO_DAYS(NOW())-TO_DAYS(p.DepartureTime)="+(2-toTodayDays).ToString();
            //temp = Db.GetListBySql<PB_DeliveryPlanValue3DTO>(strSQL).FirstOrDefault().value;
            //temp = Convert.ToDouble(temp.ToString("#0.##"));
            //res.series[0].data.Add(temp); 
            //strSQL = "SELECT IFNULL(SUM(d.PackNums),0) AS value FROM PB_TransportBillDetail d";
            //strSQL += " JOIN PB_TransportBill p ON d.ParentId = p.Id AND p.BillType='Delivery' AND TO_DAYS(NOW())-TO_DAYS(p.DepartureTime)="+(1-toTodayDays).ToString();
            //temp = Db.GetListBySql<PB_DeliveryPlanValue3DTO>(strSQL).FirstOrDefault().value;
            //temp = Convert.ToDouble(temp.ToString("#0.##"));
            //res.series[0].data.Add(temp); 
            #endregion
            #region 新代码
            //韩总要求改成重量(吨) ,牟俊明，2022.6.28
            //获取前N天发货数量汇总
            StringBuilder sql = new StringBuilder();
            sql.Append("SELECT ");
            sql.Append("date( a.DepartureTime ) CreateTime,");
            //sql.Append("IFNULL(SUM(b.PackNums),0) Value ");
            sql.Append("IFNULL(SUM(b.PackNums*c.Weight)/1000,0) Value ");
            sql.Append("");
            sql.Append("FROM ");
            sql.Append("PB_TransportBill a ");
            sql.Append("INNER JOIN PB_TransportBillDetail b ON a.Id = b.ParentId ");
            sql.Append("INNER JOIN PB_Material c ON b.MaterialId=c.Id ");
            sql.Append("WHERE ");
            sql.Append("a.BillType = 'Delivery' ");
            sql.Append("AND DATE_SUB(CURDATE(),INTERVAL " + toTodayDays + " DAY)<=date(a.DepartureTime) ");
            sql.Append("GROUP BY ");
            sql.Append("date(a.DepartureTime)");
            var data = await Db.GetListBySqlAsync<PB_TransportBillGrpDayDTO>(sql.ToString());
            //获取前7天日期
            List<string> ArrayDate = new List<string>();
            for (int i = 6; i > -1; i--)
            {
                ArrayDate.Add(DateTime.Now.AddDays(-1 * i).ToString("yyyy-MM-dd 00:00:00.000"));
            }
            //配置返回数据
            List<double> ArrayData = new List<double>();
            foreach (var item in ArrayDate)
            {
                var tmp = data.FirstOrDefault(s => s.CreateTime.Equals(item));
                ArrayData.Add(!tmp.IsNullOrEmpty() ? Convert.ToDouble(tmp.Value.ToString("#0.##")) : 0);
            }
            PB_TransportBill7DayDataDTO pB_TransportBill7DayDataDTO = new PB_TransportBill7DayDataDTO();
            pB_TransportBill7DayDataDTO.data = ArrayData;
            //修改显示格式,牟
            //res.categories = ArrayDate;
            res.categories.Clear();
            for (int i = 6; i > -1; i--)
            {
                res.categories.Add(DateTime.Now.AddDays(-1 * i).ToString("MM.dd"));
            }
            res.series.Clear();
            res.series.Add(pB_TransportBill7DayDataDTO);
            res.name = "发货量(吨)";

            #endregion
            return res;
        }
        /// <summary>
        /// 大屏显示当日装车监控照片
        /// </summary>
        /// <param name="toTodayDays">到今天的天数。-1表示昨天。默认为0</param>
        /// <returns>｛"value":"url"｝</returns>
        public async Task<List<PB_DeliveryPlanValueDTO>> GetTransportMonitor(int toTodayDays = 0)
        {
            string strSQL = $@"select b.Img AS value from (
select * from PB_TransportBill where BillType='Delivery' AND TO_DAYS(SendTime)-TO_DAYS(NOW())={toTodayDays}
)as a join PB_TransportBillImg as b on a.Id=b.BillId ORDER BY b.CreateTime desc";
            var res = await Db.GetListBySqlAsync<PB_DeliveryPlanValueDTO>(strSQL);
            return res;
        }
        /// <summary>
        /// 大屏显示30天发货省份和数量
        /// </summary>
        /// <param name="day">测试扩展天数</param>
        /// <returns>发货省份和数量</returns>
        public async Task<List<ScreenDisplayPieGraphDTO>> Get30DayDeliveryCity(int day)
        {
            string strSQL = @"SELECT r.`Name` AS name,IFNULL(SUM(td.PackNums),0) AS value FROM PB_TransportBillDetail td		
JOIN PB_TransportBill tb ON tb.Id=td.ParentId AND tb.BillType='Delivery' AND TO_DAYS(NOW())-TO_DAYS(tb.DepartureTime)<=" + (29 + day).ToString() + @"
JOIN PB_TransportBillGroup ng ON ng.ParentId=tb.Id
JOIN PB_DeliveryNotice dn ON dn.Id=ng.DeliveryNoticeId
JOIN PB_Project p ON dn.ProjectId=p.Id
JOIN Base_Region r ON p.ProvinceId = r.Id
GROUP BY p.ProvinceId";
            var res = await Db.GetListBySqlAsync<ScreenDisplayPieGraphDTO>(strSQL);
            res.ForEach(aData =>
            {
                //保留两位小数
                if (aData.name.Contains("市辖区"))
                {
                    aData.name = aData.name.Substring(0, aData.name.Length - 3);
                }
                switch (aData.name)
                {
                    case "内蒙古自治区":
                        aData.name = "内蒙古";
                        break;
                    case "广西壮族自治区":
                        aData.name = "广西省";
                        break;
                    case "西藏自治区":
                        aData.name = "西藏省";
                        break;
                    case "宁夏回族自治区":
                        aData.name = "宁夏省";
                        break;
                    case "新疆维吾尔自治区":
                        aData.name = "新疆省";
                        break;
                    default:
                        break;
                }
                aData.value = Convert.ToDouble(aData.value.ToString("#0.##"));
            });
            return res;
        }
        /// <summary>
        /// 大屏显示30天发货数量
        /// </summary>
        /// <param name="day">测试扩展天数</param>
        /// <returns>发货数量</returns>
        public ScreenDisplayValueDTO Get30DayDeliveryNums(int day)
        {
            string strSQL = @"SELECT IFNULL(SUM(td.PackNums),0) AS value FROM PB_TransportBillDetail td		
JOIN PB_TransportBill tb ON tb.Id=td.ParentId AND tb.BillType='Delivery' AND TO_DAYS(NOW())-TO_DAYS(tb.DepartureTime)<=" + (29 + day).ToString();
            var res = Db.GetListBySqlAsync<ScreenDisplayValueDTO>(strSQL).Result.FirstOrDefault();
            res.value = Convert.ToDouble(res.value.ToString("#0.##"));
            return res;
        }
        /// <summary>
        /// 大屏显示当月发货数量
        /// </summary>
        /// <param name="Month">前第几月</param>
        /// <returns></returns>
        public ScreenDisplayValueDTO GetMonthDeliveryNums(int Month)
        {
            string strSQL = @"SELECT IFNULL(SUM(td.PackNums),0) AS value FROM PB_TransportBillDetail td		
JOIN PB_TransportBill tb ON tb.Id=td.ParentId AND tb.BillType='Delivery' AND date_format(tb.DepartureTime, '%Y %m')=date_format(DATE_SUB(curdate(), INTERVAL " + Month.ToString() + @" MONTH),'%Y %m')";
            var res = Db.GetListBySqlAsync<ScreenDisplayValueDTO>(strSQL).Result.FirstOrDefault();
            res.value = Convert.ToDouble(res.value.ToString("#0.##"));
            return res;
        }
        /// <summary>
        /// 大屏显示发货城市
        /// </summary>
        /// <returns>['新乡市',[[{name: '新乡市'}, {name: '新乡市', value: 200, dataInfo: 发货总数:2000件 }], [{name: '新乡市'}, {name: '呼和浩特市', value: 100, dataInfo: 发货数:1000件 }], [{name: '新乡市'}, {name: '成都市', value: 100, dataInfo: 发货数:1000件 }]]]</returns>
        public async Task<List<List<object>>> GetDeliveryCity()
        {
            PB_DeliveryPlanCityDTO res = new PB_DeliveryPlanCityDTO();
            //实际发货总量
            string strSQL = @"SELECT IFNULL(SUM(td.PackNums),0) AS value FROM PB_TransportBillDetail td		
			JOIN PB_TransportBill tb ON tb.Id=td.ParentId AND tb.BillType='Delivery' AND TO_DAYS(tb.DepartureTime)-TO_DAYS(NOW())<=0		
			JOIN PB_TransportBillGroup ng ON ng.ParentId=tb.Id
			JOIN PB_DeliveryNotice dn ON dn.Id=ng.DeliveryNoticeId
			JOIN PB_Project p ON dn.ProjectId=p.Id
            JOIN Base_Region r ON p.CityId = r.Id";
            double total = Db.GetListBySqlAsync<PB_DeliveryPlanValue3DTO>(strSQL).Result.FirstOrDefault().value;
            //各市实际发货量
            strSQL = @"SELECT r.`Name` AS name,IFNULL(SUM(td.PackNums),0) AS dataInfo FROM PB_TransportBillDetail td		
			JOIN PB_TransportBill tb ON tb.Id=td.ParentId AND tb.BillType='Delivery' AND TO_DAYS(tb.DepartureTime)-TO_DAYS(NOW())<=0
			JOIN PB_TransportBillGroup ng ON ng.ParentId=tb.Id
			JOIN PB_DeliveryNotice dn ON dn.Id=ng.DeliveryNoticeId
			JOIN PB_Project p ON dn.ProjectId=p.Id
            JOIN Base_Region r ON p.CityId = r.Id
            GROUP BY p.CityId";
            var temp = Db.GetListBySqlAsync<PB_DeliveryPlanCityReceiveCityDTO>(strSQL);
            if (temp.Result.Count > 0)
            {
                List<object> temp2 = res.lists[0][1] as List<object>;
                //.ToString("#0.##")四舍五入保留两位小数，并去掉末尾的".0"
                temp2[0] = new List<object>() { new PB_DeliveryPlanCityDeliveryCity(), new PB_DeliveryPlanCityReceiveCityDTO { name = "邯郸市", value = 200, dataInfo = "发货总数:" + total.ToString("#0.##") + "件" } };
                total = total == 0 ? 1 : total;
                temp.Result.ForEach(aData =>
                {
                    if (aData.name.Contains("市辖区"))
                    {
                        aData.name = aData.name.Substring(0, aData.name.Length - 3);
                    }
                    int val = (int)(Convert.ToDouble(aData.dataInfo) / total * 200) == 0 ? 1 : (int)(Convert.ToDouble(aData.dataInfo) / total * 200);
                    temp2.Add(new List<object>() { new PB_DeliveryPlanCityDeliveryCity(), new PB_DeliveryPlanCityReceiveCityDTO { name = aData.name, value = val, dataInfo = "发货数:" + Convert.ToDouble(aData.dataInfo).ToString("#0.##") + "件" } });
                });
                return res.lists;
            }
            else
            {
                // throw new BusException("暂无数据");
                return null;
            }
        }
        /// <summary>
        /// 大屏显示全国爬架总量统计(机位)柱状图
        /// </summary>
        /// <returns>全国爬架总量统计(机位)</returns>
        public ScreenDisplayBarChartDTO GetStandsNumberOrderByCity()
        {
            string strSQL = @"SELECT r.`Name` AS name,IFNULL(SUM(bg.StandsNumber),0) AS value 
FROM PB_DeliveryNotice dn
JOIN PB_Project p ON dn.ProjectId=p.Id
JOIN Base_Region r ON p.CityId=r.Id
JOIN PB_Buildingnumber bg ON bg.ProjectId=p.Id
JOIN PB_TransportBillGroup ng ON dn.Id = ng.DeliveryNoticeId
JOIN PB_TransportBill tb ON tb.Id = ng.ParentId AND tb.BillType = 'Delivery' AND TO_DAYS(tb.DepartureTime)-TO_DAYS(NOW())<=0
GROUP BY r.Id 
ORDER BY SUM(bg.StandsNumber) DESC
LIMIT 15";
            List<ScreenDisplayValue4DTO> cityvalue = Db.GetListBySqlAsync<ScreenDisplayValue4DTO>(strSQL).Result;
            ScreenDisplayBarChartDTO res = new ScreenDisplayBarChartDTO();
            res.series[0].name = "全国爬架总量统计(机位)前15";
            res.categories.Clear();
            cityvalue.ForEach(aData =>
            {
                aData.name = aData.name.Contains("市辖区") ? aData.name.Substring(0, aData.name.Length - 3) : aData.name;
                aData.name = aData.name.Contains("市") ? aData.name.Substring(0, aData.name.Length - 1) : aData.name;
                aData.value = Convert.ToDouble(aData.value).ToString("#0.##");
                res.categories.Add(aData.name);
                res.series[0].data.Add(Convert.ToDouble(aData.value));
            });
            return res;
        }
        /// <summary>
        /// 大屏显示发出机位总数
        /// </summary>
        /// <returns></returns>
        public ScreenDisplayValueDTO GetDeliveryStandsNumber()
        {
            string strSQL = @"SELECT IFNULL(SUM(bg.StandsNumber),0) AS value 
FROM PB_DeliveryNotice dn
JOIN PB_Project p ON dn.ProjectId=p.Id
JOIN Base_Region r ON p.CityId=r.Id
JOIN PB_Buildingnumber bg ON bg.ProjectId=p.Id
JOIN PB_TransportBillGroup ng ON dn.Id = ng.DeliveryNoticeId
JOIN PB_TransportBill tb ON tb.Id = ng.ParentId AND tb.BillType = 'Delivery' AND TO_DAYS(tb.DepartureTime)-TO_DAYS(NOW())<=0";
            var res = Db.GetListBySqlAsync<ScreenDisplayValueDTO>(strSQL).Result.FirstOrDefault();
            res.value = Convert.ToDouble(res.value.ToString("#0.##"));
            return res;
        }
        /// <summary>`
        /// 大屏显示当月发出机位总数
        /// </summary>
        /// <param name="Month">前第几月</param>
        /// <returns></returns>
        public ScreenDisplayValueDTO GetMonthDeliveryStandsNumber(int Month)
        {
            string strSQL = @"SELECT IFNULL(SUM(bg.StandsNumber),0) AS value 
FROM PB_DeliveryNotice dn
JOIN PB_Project p ON dn.ProjectId=p.Id
JOIN Base_Region r ON p.CityId=r.Id
JOIN PB_Buildingnumber bg ON bg.ProjectId=p.Id
JOIN PB_TransportBillGroup ng ON dn.Id = ng.DeliveryNoticeId
JOIN PB_TransportBill tb ON tb.Id = ng.ParentId AND tb.BillType = 'Delivery' AND  date_format(tb.DepartureTime, '%Y %m')=date_format(DATE_SUB(curdate(), INTERVAL " + Month.ToString() + @" MONTH),'%Y %m')";
            var res = Db.GetListBySqlAsync<ScreenDisplayValueDTO>(strSQL).Result.FirstOrDefault();
            res.value = Convert.ToDouble(res.value.ToString("#0.##"));
            return res;
        }


        private List<string> GetDeptItem(string deptId, List<string> liststr, List<Base_Department> deptlist)
        {
            var dlist = deptlist.Where(x => x.ParentId == deptId).ToList();
            foreach (var item in dlist)
            {
                liststr.Add(item.Id);
                GetDeptItem(item.Id, liststr, deptlist);
            }
            return liststr;
        }

        /// <summary>
        /// 根据车牌获取车辆信息
        /// </summary>
        /// <param name="BillId">派车单Id</param>
        /// <param name="plateno">车牌</param>
        /// <param name="deptId">登录人组织Id</param>
        /// <param name="BillType">车辆类型</param>
        /// <returns></returns>
        public async Task<PB_TransportBillDataDetailDTO> GetTransportBillDataAsync(string BillId, string plateno, string deptId, string BillType)
        {
            //获取登录人法人一级组织信息
            var dpdata = await _opdept.GetOperatorDept();
            List<string> liststr = new List<string>();
            liststr.Add(dpdata.DetpId);
            //获取所有的部门信息
            List<Base_Department> deptlist = await Db.GetIQueryable<Base_Department>().ToListAsync();
            var listdata = deptlist.Where(x => x.ParentId == dpdata.DetpId).ToList();
            foreach (var item in listdata)
            {
                liststr.Add(item.Id);
                GetDeptItem(item.Id, liststr, deptlist);
            }
            //var q = await Db.GetIQueryable<PB_TransportBill>().Where(x => liststr.Contains(x.DeptId) && x.State == 1 && x.BillType == 0 && x.PlateNO == plateno).FirstOrDefaultAsync();
            Expression<Func<PB_TransportBill, PB_Vehicle, PB_TransportBillDataDetailDTO>> selectdata = (a, b) => new PB_TransportBillDataDetailDTO
            {
                PlateName = b.PlateNO
            };
            selectdata = selectdata.BuildExtendSelectExpre();
            var q = from a in Db.GetIQueryable<PB_TransportBill>().AsExpandable()
                    join b in Db.GetIQueryable<PB_Vehicle>() on a.Vehicle equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    select @selectdata.Invoke(a, b);
            if (BillType.IsNullOrEmpty())
            {
                BillType = "Delivery";
                q = q.Where(x => liststr.Contains(x.DeptId) && (x.State == 1) && x.BillType == BillType && x.Id == BillId);
            }
            else
            {
                q = q.Where(x => liststr.Contains(x.DeptId) && (x.State == 0) && x.BillType == BillType && x.Id == BillId);
            }
            var qd = await q.FirstOrDefaultAsync();
            if (qd != null)
            {
                PB_TransportBillDataDetailDTO pbdata = new PB_TransportBillDataDetailDTO();
                pbdata.Id = qd.Id;
                pbdata.CreateTime = qd.CreateTime;
                pbdata.CreatorId = qd.CreatorId;
                pbdata.Deleted = qd.Deleted;
                //pbdata.DesignListid = q.DesignListid;
                //pbdata.DispatchBillid = q.DispatchBillid;
                //pbdata.PickingBillid = q.PickingBillid;
                pbdata.Vehicle = qd.Vehicle;
                pbdata.SendTime = qd.SendTime;
                pbdata.IntoTime = qd.IntoTime;
                pbdata.DeliveryTime = qd.DeliveryTime;
                pbdata.Tunnage = qd.Tunnage;
                pbdata.DocumentMaker = qd.DocumentMaker;
                pbdata.EmptyNumber = qd.EmptyNumber;
                pbdata.EmptyTime = qd.EmptyTime;
                pbdata.NetloadNumber = qd.NetloadNumber;
                pbdata.RoughweightNumber = qd.RoughweightNumber;
                pbdata.RoughweightTime = qd.RoughweightTime;
                pbdata.WeighingPeople = qd.WeighingPeople;
                pbdata.DepartureTime = qd.DepartureTime;
                pbdata.State = qd.State;
                pbdata.DriverName = qd.DriverName;
                pbdata.Iphone = qd.Iphone;
                pbdata.PlateNO = qd.PlateNO;
                pbdata.PlateName = qd.PlateName;
                pbdata.VehicleLicense = qd.VehicleLicense;
                pbdata.DrivingLicense = qd.DrivingLicense;
                pbdata.Estimatedweight = qd.Estimatedweight;
                pbdata.EnteringPlantMan = qd.EnteringPlantMan;
                pbdata.ExFactoryMan = qd.ExFactoryMan;
                //Expression<Func<PB_TransportBillDetail, PB_PackList, PB_TransportBillDetailDataDTO>> select = (a, b) => new PB_TransportBillDetailDataDTO
                //{
                //    PackName = b.BoxName,
                //    BoxNo = b.BoxNo,
                //    Nums = b.Nums
                //};
                //select = select.BuildExtendSelectExpre();
                //var qdata = from a in Db.GetIQueryable<PB_TransportBillDetail>().AsExpandable()
                //        join b in Db.GetIQueryable<PB_PackList>() on a.PackId equals b.Id into ab
                //        from b in ab.DefaultIfEmpty()
                //        select @select.Invoke(a, b);
                //qdata = qdata.Where(x => x.ParentId == qd.Id).OrderByDescending(x => x.CreateTime);
                //string sqlMain = @"select *,ROW_NUMBER() over(order by CreateTime desc) as rowsid from ( SELECT a.Id,a.PackId,a.MaterialId,a.PackNums as Nums,b.BoxName as PackName,c.Spec as MaterialSpec,a.CreateTime FROM PB_TransportBillDetail as a join PB_PackList as b on a.PackId=b.Id join PB_Material as c on a.MaterialId=c.Id where a.ParentId='" + qd.Id + "' and b.PackageType=0 UNION ALL select '' as Id,PackId,'' as MaterialId,SUM(Nums) as Nums,PackName,'' as MaterialSpec,CreateTime from ( SELECT a.PackId,b.BoxName as PackName,a.PackNums as Nums,DATE_FORMAT(a.CreateTime,'%Y-%m-%d') as CreateTime FROM PB_TransportBillDetail as a join PB_PackList as b on a.PackId=b.Id join PB_Material as c on a.MaterialId=c.Id where a.ParentId='" + qd.Id + "' and b.PackageType=1 ) as t group by PackId,PackName,CreateTime UNION ALL select a.Id,a.PackId,a.MaterialId,a.PackNums as Nums,b.`Name` as PackName,b.Spec as MaterialSpec,a.CreateTime from PB_TransportBillDetail as a join PB_Material as b on a.MaterialId=b.Id where a.ParentId='" + qd.Id + "' and a.PackId='' ) as t";
                string sql = @"select *,ROW_NUMBER() over(order by CreateTime desc) as rowsid from ( 
SELECT a.Id,a.PackId,a.MaterialId,'' as JobId,a.PackNums as Nums,b.BoxName as PackName,c.Spec as MaterialSpec,a.CreateTime,a.TrueOrFalse,a.IsHandle,case when a.IsHandle=0 then a.PreparationNoteId else '' end as PickUpMainId FROM PB_TransportBillDetail as a join PB_PackList as b on a.PackId=b.Id join PB_Material as c on a.MaterialId=c.Id where a.ParentId='{0}' and b.PackageType=0 
UNION ALL 
select '' as Id,PackId,'' as MaterialId,'' as JobId,SUM(Nums) as Nums,PackName,'' as MaterialSpec,CreateTime,TrueOrFalse,IsHandle,case when IsHandle=0 then PreparationNoteId else '' end as PickUpMainId from ( SELECT a.PackId,b.BoxName as PackName,a.PackNums as Nums,DATE_FORMAT(a.CreateTime,'%Y-%m-%d') as CreateTime,a.TrueOrFalse,a.IsHandle,a.PreparationNoteId FROM PB_TransportBillDetail as a join PB_PackList as b on a.PackId=b.Id join PB_Material as c on a.MaterialId=c.Id where a.ParentId='{0}' and b.PackageType=1 ) as t group by PackId,PackName,CreateTime,TrueOrFalse,IsHandle,PreparationNoteId
UNION ALL 
select a.Id,a.PackId,a.MaterialId,a.JobId,a.PackNums as Nums,b.`Name` as PackName,b.Spec as MaterialSpec,a.CreateTime,a.TrueOrFalse,a.IsHandle,case when a.IsHandle=0 then a.PreparationNoteId else '' end as PickUpMainId from PB_TransportBillDetail as a join PB_Material as b on a.MaterialId=b.Id where a.ParentId='{0}' and a.PackId=''
) as t";
                string sqlMain = string.Format(sql, qd.Id);
                var transportbilldetail = await Db.GetListBySqlAsync<PB_TransportBillDetailListData>(sqlMain);
                pbdata.TransportBillDetail = transportbilldetail;
                return pbdata;
            }
            else
            {
                throw new BusException("请核对车辆信息");
            }
        }

        /// <summary>
        /// 装车
        /// </summary>
        /// <param name="data"></param>
        /// 装车包对应的发货单与派车单对应的发货通知单是否一致   2022-03-05  赵锦涛
        /// 增加扫描包容错   2022-03-06   赵锦涛
        /// <returns></returns>
        [Transactional]
        public async Task AddTransportBillDetailAsync(PB_TransportBillDetailDTO data)
        {
            //获取备货单包的信息
            //var packdata = await Db.GetIQueryable<PB_PackList>().Where(x => x.Id == data.PackQrCode.Split(',')[1].ToString()).FirstOrDefaultAsync();
            //备货单Id
            string stockupId = data.stockupQrCode.Split(',')?[1].ToString();

            string qrcodemodel = data.PackQrCode.Split(',')?[0].ToString();
            string packid = string.Empty;
            string materialId = string.Empty;
            string jobid = string.Empty;
            Base_LinkType linktypedata = await _opdept.GetLinkType("MaterialCode");
            if (qrcodemodel == "13")
            {
                packid = data.PackQrCode.Split(',')[1].ToString();
            }
            else if (qrcodemodel == "04")
            {
                var model = data.PackQrCode.Split(',');
                if (model.Length > 2)
                {
                    if (model.Length < 4)
                    {
                        throw new BusException("请扫描正确的二维码信息");
                    }
                    else
                    {
                        materialId = model?[3].ToString();
                    }
                }
                else
                {
                    materialId = model?[1].ToString();
                }
                //合并重复物料指向新的物料Id
                PB_Material materdata = await Db.GetIQueryable<PB_Material>().Where(x => x.Id == materialId).FirstOrDefaultAsync();
                if (!materdata.TransferId.IsNullOrEmpty())
                {
                    materialId = materdata.TransferId;
                }
            }
            else if (qrcodemodel == "14")
            {
                jobid = data.PackQrCode.Split(',')?[1].ToString();
            }
            //获取登录人信息
            Base_User basedata = await Db.GetIQueryable<Base_User>().Where(x => x.Id == _operator.UserId).FirstOrDefaultAsync();
            if (qrcodemodel == "13")
            {

                PB_PickUpMain pickMain = await Db.GetIQueryable<PB_PickUpMain>().Where(x => x.Id == stockupId).FirstOrDefaultAsync();
                PB_DeliveryNoticeItem NoticeItem = await Db.GetIQueryable<PB_DeliveryNoticeItem>().Where(x => x.Id == pickMain.ParentId).FirstOrDefaultAsync();

                //查询派车单对应的发货通知单
                Expression<Func<PB_TransportBill, PB_TransportBillGroup, PB_TransportBillGroupListDataDTO>> selectNoticeId = (a, b) => new PB_TransportBillGroupListDataDTO
                {
                    DeliveryNoticeId = b.DeliveryNoticeId
                };
                selectNoticeId = selectNoticeId.BuildExtendSelectExpre();
                var qNoticeId = from a in Db.GetIQueryable<PB_TransportBill>().AsExpandable()
                                join b in Db.GetIQueryable<PB_TransportBillGroup>() on a.Id equals b.ParentId into ab
                                from b in ab.DefaultIfEmpty()
                                select @selectNoticeId.Invoke(a, b);
                var BillGrouplist = await qNoticeId.Where(x => x.Id == data.BillId && x.State == 1).ToListAsync();
                //匹配包与派车单对应的发货通知单是否存在
                var groupdata = BillGrouplist.Find(x => x.DeliveryNoticeId == NoticeItem.ParentId);
                if (groupdata == null)
                {
                    throw new BusException("请核对车辆对应的发货通知单");
                }

                var PackListdata = await Db.GetIQueryable<PB_PackList>().Where(x => x.Id == packid).FirstOrDefaultAsync();
                if (PackListdata.Status == 5)
                {
                    throw new BusException("包码已作废,请做补码处理");
                }
                if (PackListdata.PackageType == 0)
                {
                    Expression<Func<PB_UnLoadList, PB_PackList, PB_PickUpList, LoadingPackageDTO>> select = (a, b, c) => new LoadingPackageDTO
                    {
                        stockupId = c.Id,
                        subId = c.SubId,
                        PickMainId = c.ParentId
                    };
                    select = select.BuildExtendSelectExpre();
                    var qdata = from a in Db.GetIQueryable<PB_UnLoadList>().AsExpandable()
                                join b in Db.GetIQueryable<PB_PackList>() on a.PackId equals b.Id into ab
                                from b in ab.DefaultIfEmpty()
                                join c in Db.GetIQueryable<PB_PickUpList>() on a.ParentId equals c.Id into bc
                                from c in bc.DefaultIfEmpty()
                                select @select.Invoke(a, b, c);
                    var packdata = await qdata.Where(x => x.PackId == packid && x.PickMainId == stockupId).FirstOrDefaultAsync();
                    if (!packdata.IsNullOrEmpty())
                    {
                        var billdata = await Db.GetIQueryable<PB_TransportBillDetail>().Where(x => x.PackId == packid).FirstOrDefaultAsync();
                        if (billdata.IsNullOrEmpty())
                        {
                            //装车
                            PB_TransportBillDetail pbdata = new PB_TransportBillDetail();
                            pbdata.Id = IdHelper.GetId();
                            pbdata.ParentId = data.BillId;
                            pbdata.DesignDetailId = packdata.subId;
                            pbdata.PreparationNoteId = stockupId;
                            pbdata.PackId = packid;
                            pbdata.MaterialId = packdata.MaterialId;
                            pbdata.PretendCarUserId = _operator.UserId;
                            pbdata.PretendCarUserName = basedata.RealName;
                            pbdata.PretendCarTime = DateTime.Now;
                            pbdata.PackNums = packdata.Nums;
                            pbdata.ReceiptQuantity = 0;
                            pbdata.CreatorId = _operator.UserId;
                            pbdata.CreatorName = basedata.RealName;
                            pbdata.CreateTime = DateTime.Now;
                            pbdata.Deleted = false;
                            pbdata.Status = 0;
                            pbdata.JobId = "";
                            pbdata.TrueOrFalse = true;
                            pbdata.IsHandle = true;
                            await Db.InsertAsync(pbdata);
                            List<PB_TransportBillDetail> listdata = await Db.GetIQueryable<PB_TransportBillDetail>().Where(x => x.ParentId == data.BillId).ToListAsync();
                            if (listdata.Count == 1)
                            {
                                string sqlMain = @"update PB_TransportBill set LoadingStartTime=NOW() where id='" + data.BillId + "'";
                                await ExecuteSqlAsync(sqlMain);
                            }
                        }
                        else
                        {
                            throw new BusException("包已装车或已装其他车辆");
                        }
                    }
                    else
                    {
                        var billdata = await Db.GetIQueryable<PB_TransportBillDetail>().Where(x => x.PackId == packid).FirstOrDefaultAsync();
                        if (billdata.IsNullOrEmpty())
                        {
                            //装车
                            PB_TransportBillDetail pbdata = new PB_TransportBillDetail();
                            pbdata.Id = IdHelper.GetId();
                            pbdata.ParentId = data.BillId;
                            pbdata.DesignDetailId = "";
                            pbdata.PreparationNoteId = data.PickUpMainId.IsNullOrEmpty() ? stockupId : data.PickUpMainId;
                            pbdata.PackId = packid;
                            pbdata.MaterialId = PackListdata.MaterialId;
                            pbdata.PretendCarUserId = _operator.UserId;
                            pbdata.PretendCarUserName = basedata.RealName;
                            pbdata.PretendCarTime = DateTime.Now;
                            pbdata.PackNums = PackListdata.Nums;
                            pbdata.ReceiptQuantity = 0;
                            pbdata.CreatorId = _operator.UserId;
                            pbdata.CreatorName = basedata.RealName;
                            pbdata.CreateTime = DateTime.Now;
                            pbdata.Deleted = false;
                            pbdata.Status = 0;
                            pbdata.JobId = "";
                            pbdata.TrueOrFalse = data.TrueOrFalse;
                            pbdata.IsHandle = false;
                            await Db.InsertAsync(pbdata);
                            List<PB_TransportBillDetail> listdata = await Db.GetIQueryable<PB_TransportBillDetail>().Where(x => x.ParentId == data.BillId).ToListAsync();
                            if (listdata.Count == 1)
                            {
                                string sqlMain = @"update PB_TransportBill set LoadingStartTime=NOW() where id='" + data.BillId + "'";
                                await ExecuteSqlAsync(sqlMain);
                            }
                        }
                        else
                        {
                            throw new BusException("包已装车或已装其他车辆");
                        }
                        //throw new BusException("请检查包是否与备货单匹配");
                    }
                }
                else if (PackListdata.PackageType == 1)
                {
                    Expression<Func<PB_UnLoadList, PB_PickUpList, LoadingPackageDTO>> select = (a, c) => new LoadingPackageDTO
                    {
                        stockupId = c.Id,
                        subId = c.SubId,
                        PickMainId = c.ParentId
                    };
                    select = select.BuildExtendSelectExpre();
                    var qdata = from a in Db.GetIQueryable<PB_UnLoadList>().AsExpandable()
                                join c in Db.GetIQueryable<PB_PickUpList>() on a.ParentId equals c.Id into bc
                                from c in bc.DefaultIfEmpty()
                                select @select.Invoke(a, c);
                    var packdata = await qdata.Where(x => x.PackId == packid && x.PickMainId == stockupId).ToListAsync();
                    if (packdata.Count > 0)
                    {
                        var billdata = await Db.GetIQueryable<PB_TransportBillDetail>().Where(x => x.ParentId == data.BillId && x.PackId == packid).FirstOrDefaultAsync();
                        List<PB_TransportBillDetail> BillDetaillistdata = new List<PB_TransportBillDetail>();
                        if (billdata.IsNullOrEmpty())
                        {
                            foreach (var item in packdata)
                            {
                                //装车
                                PB_TransportBillDetail pbdata = new PB_TransportBillDetail();
                                pbdata.Id = IdHelper.GetId();
                                pbdata.ParentId = data.BillId;
                                pbdata.DesignDetailId = item.subId;
                                pbdata.PreparationNoteId = stockupId;
                                pbdata.PackId = item.PackId;
                                pbdata.MaterialId = item.MaterialId;
                                pbdata.PretendCarUserId = _operator.UserId;
                                pbdata.PretendCarUserName = basedata.RealName;
                                pbdata.PretendCarTime = DateTime.Now;
                                pbdata.PackNums = item.Nums;
                                pbdata.ReceiptQuantity = 0;
                                pbdata.CreatorId = _operator.UserId;
                                pbdata.CreatorName = basedata.RealName;
                                pbdata.CreateTime = DateTime.Now;
                                pbdata.Deleted = false;
                                pbdata.Status = 0;
                                pbdata.JobId = "";
                                pbdata.TrueOrFalse = true;
                                pbdata.IsHandle = true;
                                BillDetaillistdata.Add(pbdata);
                            }
                            await Db.InsertAsync<PB_TransportBillDetail>(BillDetaillistdata);
                            List<PB_TransportBillDetail> listdata = await Db.GetIQueryable<PB_TransportBillDetail>().Where(x => x.ParentId == data.BillId).ToListAsync();
                            if (listdata.Count == 1)
                            {
                                string sqlMain = @"update PB_TransportBill set LoadingStartTime=NOW() where Id='" + data.BillId + "'";
                                await ExecuteSqlAsync(sqlMain);
                            }
                        }
                        else
                        {
                            throw new BusException("包已装车或已装其他车辆");
                        }
                    }
                    else
                    {
                        List<PB_PackMaterialCount> PackMaterialCount = await Db.GetIQueryable<PB_PackMaterialCount>().Where(x => x.PackId == packid).ToListAsync();
                        var billdata = await Db.GetIQueryable<PB_TransportBillDetail>().Where(x => x.ParentId == data.BillId && x.PackId == packid).FirstOrDefaultAsync();
                        List<PB_TransportBillDetail> BillDetaillistdata = new List<PB_TransportBillDetail>();
                        if (billdata.IsNullOrEmpty())
                        {
                            foreach (var item in PackMaterialCount)
                            {
                                //装车
                                PB_TransportBillDetail pbdata = new PB_TransportBillDetail();
                                pbdata.Id = IdHelper.GetId();
                                pbdata.ParentId = data.BillId;
                                pbdata.DesignDetailId = "";
                                pbdata.PreparationNoteId = data.PickUpMainId.IsNullOrEmpty() ? stockupId : data.PickUpMainId;
                                pbdata.PackId = item.PackId;
                                pbdata.MaterialId = item.MaterialId;
                                pbdata.PretendCarUserId = _operator.UserId;
                                pbdata.PretendCarUserName = basedata.RealName;
                                pbdata.PretendCarTime = DateTime.Now;
                                pbdata.PackNums = item.Nums;
                                pbdata.ReceiptQuantity = 0;
                                pbdata.CreatorId = _operator.UserId;
                                pbdata.CreatorName = basedata.RealName;
                                pbdata.CreateTime = DateTime.Now;
                                pbdata.Deleted = false;
                                pbdata.Status = 0;
                                pbdata.JobId = "";
                                pbdata.TrueOrFalse = data.TrueOrFalse;
                                pbdata.IsHandle = false;
                                BillDetaillistdata.Add(pbdata);
                            }
                            await Db.InsertAsync<PB_TransportBillDetail>(BillDetaillistdata);
                            List<PB_TransportBillDetail> listdata = await Db.GetIQueryable<PB_TransportBillDetail>().Where(x => x.ParentId == data.BillId).ToListAsync();
                            if (listdata.Count == 1)
                            {
                                string sqlMain = @"update PB_TransportBill set LoadingStartTime=NOW() where Id='" + data.BillId + "'";
                                await ExecuteSqlAsync(sqlMain);
                            }
                        }
                        else
                        {
                            throw new BusException("包已装车或已装其他车辆");
                        }
                        //throw new BusException("请检查包是否与备货单匹配");
                    }
                }
            }
            else if (qrcodemodel == "04")
            {
                //合并重复物料指向新的物料Id
                PB_Material materdata = await Db.GetIQueryable<PB_Material>().Where(x => x.Id == materialId).FirstOrDefaultAsync();
                if (!materdata.TransferId.IsNullOrEmpty())
                {
                    materialId = materdata.TransferId;
                }
                //查询备货单已备数据
                List<PB_PickUpList> picklist = await Db.GetIQueryable<PB_PickUpList>().Where(x => x.ParentId == stockupId && x.MaterialId == materialId).ToListAsync();
                var pickmaterial = picklist.GroupBy(x => new { x.MaterialId, x.SubId }).Select(x => new { MaterialId = x.Key.MaterialId, SubId = x.Key.SubId, ReadyNums = x.Sum(i => i.ReadyNums) }).FirstOrDefault();
                //查询已装数据
                List<PB_TransportBillDetail> tbdata = await Db.GetIQueryable<PB_TransportBillDetail>().Where(x => x.ParentId == data.BillId && x.MaterialId == materialId && x.PreparationNoteId == stockupId).ToListAsync();
                var tbmaterial = tbdata.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId, Nums = x.Sum(i => i.PackNums) }).FirstOrDefault();

                List<PB_TransportBillDetail> TransportBillDetailList = new List<PB_TransportBillDetail>();
                if (!pickmaterial.IsNullOrEmpty())
                {
                    Double? dnums = data.Nums + (tbmaterial.IsNullOrEmpty() ? 0 : tbmaterial.Nums);
                    if (dnums > pickmaterial.ReadyNums)
                    {
                        PB_TransportBillDetail BillDetail = new PB_TransportBillDetail();
                        BillDetail.Id = IdHelper.GetId();
                        BillDetail.ParentId = data.BillId;
                        BillDetail.DesignDetailId = pickmaterial.IsNullOrEmpty() ? "" : pickmaterial.SubId;
                        BillDetail.PreparationNoteId = stockupId;
                        BillDetail.PackId = "";
                        BillDetail.MaterialId = materialId;
                        BillDetail.PretendCarUserId = _operator.UserId;
                        BillDetail.PretendCarUserName = basedata.RealName;
                        BillDetail.PretendCarTime = DateTime.Now;
                        BillDetail.PackNums = dnums - (tbmaterial.IsNullOrEmpty() ? pickmaterial.ReadyNums : tbmaterial.Nums);
                        BillDetail.ReceiptQuantity = 0;
                        BillDetail.CreatorId = _operator.UserId;
                        BillDetail.CreatorName = basedata.RealName;
                        BillDetail.CreateTime = DateTime.Now;
                        BillDetail.Deleted = false;
                        BillDetail.Status = 0;
                        BillDetail.JobId = "";
                        BillDetail.TrueOrFalse = false;
                        BillDetail.IsHandle = false;
                        TransportBillDetailList.Add(BillDetail);
                        data.Nums -= dnums - (tbmaterial.IsNullOrEmpty() ? pickmaterial.ReadyNums : tbmaterial.Nums);
                    }
                    if (data.Nums > 0)
                    {
                        //单个物料装车
                        PB_TransportBillDetail pbdata = new PB_TransportBillDetail();
                        pbdata.Id = IdHelper.GetId();
                        pbdata.ParentId = data.BillId;
                        pbdata.DesignDetailId = pickmaterial.IsNullOrEmpty() ? "" : pickmaterial.SubId;
                        pbdata.PreparationNoteId = stockupId;
                        pbdata.PackId = "";
                        pbdata.MaterialId = materialId;
                        pbdata.PretendCarUserId = _operator.UserId;
                        pbdata.PretendCarUserName = basedata.RealName;
                        pbdata.PretendCarTime = DateTime.Now;
                        pbdata.PackNums = data.Nums;
                        pbdata.ReceiptQuantity = 0;
                        pbdata.CreatorId = _operator.UserId;
                        pbdata.CreatorName = basedata.RealName;
                        pbdata.CreateTime = DateTime.Now;
                        pbdata.Deleted = false;
                        pbdata.Status = 0;
                        pbdata.JobId = "";
                        pbdata.TrueOrFalse = pickmaterial.IsNullOrEmpty() ? false : true;
                        pbdata.IsHandle = pickmaterial.IsNullOrEmpty() ? false : true;
                        TransportBillDetailList.Add(pbdata);
                    }
                }
                else
                {
                    //单个物料装车
                    PB_TransportBillDetail pbdata = new PB_TransportBillDetail();
                    pbdata.Id = IdHelper.GetId();
                    pbdata.ParentId = data.BillId;
                    pbdata.DesignDetailId = pickmaterial.IsNullOrEmpty() ? "" : pickmaterial.SubId;
                    pbdata.PreparationNoteId = stockupId;
                    pbdata.PackId = "";
                    pbdata.MaterialId = materialId;
                    pbdata.PretendCarUserId = _operator.UserId;
                    pbdata.PretendCarUserName = basedata.RealName;
                    pbdata.PretendCarTime = DateTime.Now;
                    pbdata.PackNums = data.Nums;
                    pbdata.ReceiptQuantity = 0;
                    pbdata.CreatorId = _operator.UserId;
                    pbdata.CreatorName = basedata.RealName;
                    pbdata.CreateTime = DateTime.Now;
                    pbdata.Deleted = false;
                    pbdata.Status = 0;
                    pbdata.JobId = "";
                    pbdata.TrueOrFalse = pickmaterial.IsNullOrEmpty() ? false : true;
                    pbdata.IsHandle = pickmaterial.IsNullOrEmpty() ? false : true;
                    TransportBillDetailList.Add(pbdata);
                }
                await Db.InsertAsync<PB_TransportBillDetail>(TransportBillDetailList);
                List<PB_TransportBillDetail> listdata = await Db.GetIQueryable<PB_TransportBillDetail>().Where(x => x.ParentId == data.BillId).ToListAsync();
                if (listdata.Count == 1)
                {
                    string sqlMain = @"update PB_TransportBill set LoadingStartTime=NOW() where Id='" + data.BillId + "'";
                    await ExecuteSqlAsync(sqlMain);
                }
            }
            else if (qrcodemodel == "14")
            {
                if (linktypedata.Whether == true)
                {
                    //获取成品信息
                    PB_JobBookingQrCode jobdata = await Db.GetIQueryable<PB_JobBookingQrCode>().Where(x => x.Id == jobid).FirstOrDefaultAsync();
                    if (jobdata.IsNullOrEmpty())
                    {
                        throw new BusException("成品码已作废,请做补码处理");
                    }
                    if (jobdata.PackStatus == 1)
                    {
                        throw new BusException("成品码已作废,请做补码处理");
                    }
                    //获取备货单明细信息
                    var detaildata = await Db.GetIQueryable<PB_PickUpList>().Where(x => x.ParentId == stockupId && x.MaterialId == jobdata.MaterialId).ToListAsync();
                    //if (detaildata.Count == 0)
                    //{
                    //    throw new BusException("请检查扫描的成品是否与备货单中的物料匹配");
                    //}

                    var pickmaterial = detaildata.GroupBy(x => new { x.MaterialId, x.SubId }).Select(x => new { MaterialId = x.Key.MaterialId, SubId = x.Key.SubId, ReadyNums = x.Sum(i => i.ReadyNums) }).FirstOrDefault();

                    //IT_LocalDetail LocalDetail = await Db.GetIQueryable<IT_LocalDetail>().Where(x => x.JobId == jobid).FirstOrDefaultAsync();
                    //if (!LocalDetail.IsNullOrEmpty())
                    //{
                    //    throw new BusException("请检查成品是否出库");
                    //}

                    PB_TransportBillDetail billdetail = await Db.GetIQueryable<PB_TransportBillDetail>().Where(x => x.JobId == jobid).FirstOrDefaultAsync();
                    if (!billdetail.IsNullOrEmpty())
                    {
                        throw new BusException("成品已装车或已装其他车辆");
                    }

                    //查询物料装车数量
                    List<PB_TransportBillDetail> TransportBillDetail = await Db.GetIQueryable<PB_TransportBillDetail>().Where(x => x.ParentId == data.BillId && x.PreparationNoteId == stockupId && x.MaterialId == jobdata.MaterialId).ToListAsync();
                    var tbddata = TransportBillDetail.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId, Nums = x.Sum(i => i.PackNums) }).FirstOrDefault();
                    //数量=已装车数量+本次装车数量
                    double? dnum = 0;
                    if (tbddata.IsNullOrEmpty())
                    {
                        dnum = data.Nums;
                    }
                    else
                    {
                        dnum = tbddata.Nums + 1;
                    }

                    //单个成品物料装车
                    PB_TransportBillDetail pbdata = new PB_TransportBillDetail();
                    pbdata.Id = IdHelper.GetId();
                    pbdata.ParentId = data.BillId;
                    pbdata.DesignDetailId = pickmaterial.IsNullOrEmpty() ? "" : pickmaterial.SubId;
                    pbdata.PreparationNoteId = data.PickUpMainId.IsNullOrEmpty() ? stockupId : data.PickUpMainId;
                    pbdata.PackId = "";
                    pbdata.MaterialId = jobdata.MaterialId;
                    pbdata.PretendCarUserId = _operator.UserId;
                    pbdata.PretendCarUserName = basedata.RealName;
                    pbdata.PretendCarTime = DateTime.Now;
                    pbdata.PackNums = 1;
                    pbdata.ReceiptQuantity = 0;
                    pbdata.CreatorId = _operator.UserId;
                    pbdata.CreatorName = basedata.RealName;
                    pbdata.CreateTime = DateTime.Now;
                    pbdata.Deleted = false;
                    pbdata.Status = 0;
                    pbdata.JobId = jobid;
                    pbdata.TrueOrFalse = data.TrueOrFalse;
                    pbdata.IsHandle = data.PickUpMainId.IsNullOrEmpty() ? true : false;
                    await Db.InsertAsync(pbdata);
                    List<PB_TransportBillDetail> listdata = await Db.GetIQueryable<PB_TransportBillDetail>().Where(x => x.ParentId == data.BillId).ToListAsync();
                    if (listdata.Count == 1)
                    {
                        string sqlMain = @"update PB_TransportBill set LoadingStartTime=NOW() where Id='" + data.BillId + "'";
                        await ExecuteSqlAsync(sqlMain);
                    }
                }
                else
                {
                    //查询成品物料信息
                    PB_JobBookingQrCode jobdata = await Db.GetIQueryable<PB_JobBookingQrCode>().Where(x => x.Id == jobid).FirstOrDefaultAsync();
                    if (jobdata == null)
                    {
                        throw new BusException("请检查成品信息是否正确");
                    }
                    //查询备货单明细物料信息
                    PB_PickUpList PickUpList = await Db.GetIQueryable<PB_PickUpList>().Where(x => x.ParentId == stockupId && x.MaterialId == jobdata.MaterialId).FirstOrDefaultAsync();
                    //单个成品物料装车
                    PB_TransportBillDetail pbdata = new PB_TransportBillDetail();
                    pbdata.Id = IdHelper.GetId();
                    pbdata.ParentId = data.BillId;
                    pbdata.DesignDetailId = PickUpList.IsNullOrEmpty() ? "" : PickUpList.SubId;
                    pbdata.PreparationNoteId = stockupId;
                    pbdata.PackId = "";
                    pbdata.MaterialId = jobdata.MaterialId;
                    pbdata.PretendCarUserId = _operator.UserId;
                    pbdata.PretendCarUserName = basedata.RealName;
                    pbdata.PretendCarTime = DateTime.Now;
                    pbdata.PackNums = data.Nums;
                    pbdata.ReceiptQuantity = 0;
                    pbdata.CreatorId = _operator.UserId;
                    pbdata.CreatorName = basedata.RealName;
                    pbdata.CreateTime = DateTime.Now;
                    pbdata.Deleted = false;
                    pbdata.Status = 0;
                    pbdata.JobId = "";
                    pbdata.TrueOrFalse = PickUpList.IsNullOrEmpty() ? false : true;
                    pbdata.IsHandle = PickUpList.IsNullOrEmpty() ? false : true;
                    await Db.InsertAsync(pbdata);
                    List<PB_TransportBillDetail> listdata = await Db.GetIQueryable<PB_TransportBillDetail>().Where(x => x.ParentId == data.BillId).ToListAsync();
                    if (listdata.Count == 1)
                    {
                        string sqlMain = @"update PB_TransportBill set LoadingStartTime=NOW() where Id='" + data.BillId + "'";
                        await ExecuteSqlAsync(sqlMain);
                    }
                }
            }
        }

        /// <summary>
        /// 删除车辆已装车的明细
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task DeleteBillDataDetailAsync(PB_TransportBillDetailListData data)
        {
            if (data.PackId == "")
            {
                string sqlMain = @" delete from PB_TransportBillDetail where Id='" + data.Id + "' ";
                await ExecuteSqlAsync(sqlMain);
            }
            else
            {
                string sqlMain = @" delete from PB_TransportBillDetail where PackId='" + data.PackId + "' ";
                await ExecuteSqlAsync(sqlMain);
            }
        }

        /// <summary>
        /// 装车扫描包根据备货单获取包信息
        /// </summary>
        /// <param name="PackQrCode">包二维码</param>
        /// <param name="stockupQrCode">备货单二维码</param>
        /// <param name="BillId">派车单Id</param>
        /// <returns></returns>
        public async Task<TranBillPackDTO> GetTranBillPackDataAsync(string PackQrCode, string stockupQrCode, string BillId)
        {
            //包Id
            string packid = PackQrCode.Split(',')?[1].ToString();
            //备货单Id
            string stockupid = stockupQrCode.Split(',')?[1].ToString();
            string sqlMain = @"select c.Id as PackId,c.BoxName,c.Nums from PB_PickUpList as a left join PB_UnLoadList as b on a.Id=b.ParentId left join PB_PackList as c on b.PackId=c.Id  where a.ParentId='" + stockupid + "' and b.PackId='" + packid + "' group by c.Id,c.BoxName,c.Nums";
            var stockpackdata = await Db.GetListBySqlAsync<TranBillPackDTO>(sqlMain);
            if (stockpackdata.Count > 0)
            {
                Expression<Func<PB_PackMaterialCount, PB_Material, TranBillPackDetailDTO>> select = (a, b) => new TranBillPackDetailDTO
                {
                    PackId = a.PackId,
                    MaterialId = a.MaterialId,
                    MaterialName = b.Name,
                    MaterialCode = b.Code,
                    MaterialSpec = b.Spec,
                    ProductCode = b.ProductCode,
                    Nums = a.Nums
                };
                select = select.BuildExtendSelectExpre();
                var q = from a in Db.GetIQueryable<PB_PackMaterialCount>().AsExpandable()
                        join b in Db.GetIQueryable<PB_Material>() on a.MaterialId equals b.Id into ab
                        from b in ab.DefaultIfEmpty()
                        select @select.Invoke(a, b);
                List<TranBillPackDetailDTO> TranBillPackDetail = await q.Where(x => x.PackId == packid).ToListAsync();

                //获取备货单的已备货数量
                string unsql = @"select * from PB_UnLoadList where ParentId in (select Id from PB_PickUpList where ParentId='" + stockupid + "')";
                List<PB_UnLoadList> UnLoadList = await Db.GetListBySqlAsync<PB_UnLoadList>(unsql);
                var unlist = UnLoadList.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId, Nums = x.Sum(i => i.Nums) }).ToList();

                //获取已装车数量
                List<PB_TransportBillDetail> TransportBillDetail = await Db.GetIQueryable<PB_TransportBillDetail>().Where(x => x.ParentId == BillId && x.Status == 0).ToListAsync();
                var BillDetail = TransportBillDetail.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId, Nums = x.Sum(i => i.PackNums) }).ToList();

                foreach (var item in TranBillPackDetail)
                {
                    var itemdata = unlist.Where(x => x.MaterialId == item.MaterialId).FirstOrDefault();
                    var billdata = BillDetail.Where(x => x.MaterialId == item.MaterialId).FirstOrDefault();
                    if (itemdata != null)
                    {
                        item.RemainingQuantity = (itemdata.Nums - (billdata == null ? 0 : billdata.Nums));
                    }
                }

                TranBillPackDTO TranBillPack = new TranBillPackDTO();
                TranBillPack.PackId = stockpackdata.FirstOrDefault().PackId;
                TranBillPack.PackQrCode = PackQrCode;
                TranBillPack.BoxName = stockpackdata.FirstOrDefault().BoxName;
                TranBillPack.Nums = stockpackdata.FirstOrDefault().Nums;
                TranBillPack.TranBillPackDetail = TranBillPackDetail;
                TranBillPack.TrueOrFalse = true;
                return TranBillPack;
            }
            else
            {
                Expression<Func<PB_PackMaterialCount, PB_Material, TranBillPackDetailDTO>> select = (a, b) => new TranBillPackDetailDTO
                {
                    PackId = a.PackId,
                    MaterialId = a.MaterialId,
                    MaterialName = b.Name,
                    MaterialCode = b.Code,
                    MaterialSpec = b.Spec,
                    ProductCode = b.ProductCode,
                    Nums = a.Nums,
                    RemainingQuantity = 0
                };
                select = select.BuildExtendSelectExpre();
                var q = from a in Db.GetIQueryable<PB_PackMaterialCount>().AsExpandable()
                        join b in Db.GetIQueryable<PB_Material>() on a.MaterialId equals b.Id into ab
                        from b in ab.DefaultIfEmpty()
                        select @select.Invoke(a, b);
                List<TranBillPackDetailDTO> TranBillPackDetail = await q.Where(x => x.PackId == packid).ToListAsync();

                PB_PackList PackList = await Db.GetIQueryable<PB_PackList>().Where(x => x.Id == packid).FirstOrDefaultAsync();
                if (PackList.IsNullOrEmpty())
                {
                    throw new BusException("请检查包是否存在");
                }
                TranBillPackDTO TranBillPack = new TranBillPackDTO();

                //查询包是否是其他备货单备货出库
                List<PB_UnLoadList> UnLoadList = await Db.GetIQueryable<PB_UnLoadList>().Where(x => x.PackId == packid).ToListAsync();
                if (UnLoadList.Count > 0)
                {
                    PB_PickUpList PickUpList = await Db.GetIQueryable<PB_PickUpList>().Where(x => x.Id == UnLoadList.FirstOrDefault().ParentId).FirstOrDefaultAsync();
                    if (!PickUpList.IsNullOrEmpty())
                    {
                        TranBillPack.PickUpMainId = PickUpList.ParentId;
                        TranBillPack.TrueOrFalse = true;
                    }
                }
                else
                {
                    TranBillPack.TrueOrFalse = false;
                }
                //if (PackList.Status != 4)
                //{
                //    throw new BusException("请检查包是否出库");
                //}
                TranBillPack.PackId = packid;
                TranBillPack.PackQrCode = PackQrCode;
                TranBillPack.BoxName = PackList.BoxName;
                TranBillPack.Nums = PackList.Nums;
                TranBillPack.TranBillPackDetail = TranBillPackDetail;
                return TranBillPack;
                //throw new BusException("请扫描备货单已备货的包信息");
            }
        }

        /// <summary>
        /// 装车扫描单个成品获取物料数量
        /// </summary>
        /// <param name="BillId">派车单Id</param>
        /// <param name="JobQrCode">单个成品二维码</param>
        /// <param name="stockupQrCode">备货单二维码</param>
        /// <returns></returns>
        public async Task<TranBillMaterialDTO> GetTranBillMaterialAsync(string BillId, string JobQrCode, string stockupQrCode)
        {
            //单个成品Id
            string jobid = JobQrCode.Split(',')?[1].ToString();
            //备货单Id
            string stockupid = stockupQrCode.Split(',')?[1].ToString();
            //根据成品Id获取信息
            PB_JobBookingQrCode jobdata = await Db.GetIQueryable<PB_JobBookingQrCode>().Where(x => x.Id == jobid).FirstOrDefaultAsync();
            if (jobdata != null)
            {
                PB_PickUpList PickUpList = await Db.GetIQueryable<PB_PickUpList>().Where(x => x.ParentId == stockupid && x.MaterialId == jobdata.MaterialId).FirstOrDefaultAsync();
                PB_Material Material = await Db.GetIQueryable<PB_Material>().Where(x => x.Id == jobdata.MaterialId).FirstOrDefaultAsync();
                if (PickUpList.IsNullOrEmpty())
                {
                    TranBillMaterialDTO tbdata = new TranBillMaterialDTO();
                    tbdata.MaterialId = jobdata.MaterialId;
                    tbdata.MaterialCode = Material.Code;
                    tbdata.MaterialName = Material.Name;
                    tbdata.MaterialSpec = Material.Spec;
                    tbdata.PackId = "";
                    tbdata.PackQrCode = JobQrCode;
                    tbdata.Nums = 1;
                    tbdata.RemainingQuantity = 0;
                    //查询成品备货信息
                    PB_UnLoadList UnLoadList = await Db.GetIQueryable<PB_UnLoadList>().Where(x => x.JobId == jobid).FirstOrDefaultAsync();
                    if (!UnLoadList.IsNullOrEmpty())
                    {
                        PB_PickUpList itemdata = await Db.GetIQueryable<PB_PickUpList>().Where(x => x.Id == UnLoadList.ParentId).FirstOrDefaultAsync();
                        if (!itemdata.IsNullOrEmpty())
                        {
                            tbdata.PickUpMainId = itemdata.ParentId;
                        }
                        tbdata.TrueOrFalse = true;
                    }
                    else
                    {
                        tbdata.TrueOrFalse = false;
                    }
                    return tbdata;
                }
                else
                {
                    //获取当前装车物料信息
                    List<PB_TransportBillDetail> TransportBillDetail = await Db.GetIQueryable<PB_TransportBillDetail>().Where(x => x.ParentId == BillId && x.MaterialId == jobdata.MaterialId).ToListAsync();
                    //汇总当前物料装车数量
                    var billdetail = TransportBillDetail.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId, Nums = x.Sum(i => i.PackNums) }).FirstOrDefault();
                    TranBillMaterialDTO tbdata = new TranBillMaterialDTO();
                    tbdata.MaterialId = jobdata.MaterialId;
                    tbdata.MaterialCode = Material.Code;
                    tbdata.MaterialName = Material.Name;
                    tbdata.MaterialSpec = Material.Spec;
                    tbdata.PackId = "";                    
                    tbdata.PackQrCode = JobQrCode;
                    tbdata.Nums = PickUpList.ReadyNums - (billdetail == null ? 0 : billdetail.Nums);
                    tbdata.RemainingQuantity = (PickUpList.ReadyNums - (billdetail == null ? 0 : billdetail.Nums));
                    //查询成品备货信息
                    PB_UnLoadList UnLoadList = await Db.GetIQueryable<PB_UnLoadList>().Where(x => x.JobId == jobid).FirstOrDefaultAsync();
                    if (!UnLoadList.IsNullOrEmpty())
                    {
                        PB_PickUpList itemdata = await Db.GetIQueryable<PB_PickUpList>().Where(x => x.Id == UnLoadList.ParentId).FirstOrDefaultAsync();
                        if (!itemdata.IsNullOrEmpty())
                        {
                            if (PickUpList.ParentId != itemdata.ParentId)
                            {
                                tbdata.PickUpMainId = itemdata.ParentId;
                            }
                        }
                        tbdata.TrueOrFalse = true;
                    }
                    else
                    {
                        tbdata.TrueOrFalse = false;
                    }
                    return tbdata;
                }
            }
            else
            {
                throw new BusException("请检查成品码是否存在");
            }
        }

        /// <summary>
        /// 装车扫描单个物料
        /// </summary>
        /// <param name="BillId">车辆Id</param>
        /// <param name="qrcode">单个物料二维码</param>
        /// <param name="stockupQrCode">备货单二维码</param>
        /// <returns></returns>
        public async Task<PickListMaterialDTO> GetMaterialDataAsync(string BillId, string qrcode, string stockupQrCode)
        {
            string stockId = stockupQrCode.Split(',')?[1].ToString();
            string materialId = "";
            string model = qrcode.Split(',')?[0].ToString();
            if (model == "04")
            {
                if (model.Length > 2)
                {
                    if (model.Length < 4)
                    {
                        throw new BusException("请扫描正确的二维码信息");
                    }
                    else
                    {
                        materialId = qrcode.Split(',')?[3].ToString();
                    }
                }
                else
                {
                    materialId = qrcode.Split(',')?[1].ToString();
                }
                //合并重复物料指向新的物料Id
                PB_Material materdata = await Db.GetIQueryable<PB_Material>().Where(x => x.Id == materialId).FirstOrDefaultAsync();
                if (materdata.IsNullOrEmpty())
                {
                    throw new BusException("请检查物料是否存在");
                }
                if (!materdata.TransferId.IsNullOrEmpty())
                {
                    materialId = materdata.TransferId;
                }
                string sql = @"select t.PickMainId,Id,`Name`,`Code`,Spec,case when (ReadyNums-IFNULL(c.Nums,0))>0 then (ReadyNums-IFNULL(c.Nums,0)) else 0 end as Nums from (
select a.ParentId as PickMainId,a.MaterialId as Id,b.`Name`,b.`Code`,b.Spec,SUM(a.ReadyNums) as ReadyNums from PB_PickUpList as a
left join PB_Material as b on a.MaterialId=b.Id
where a.ParentId='{0}' and a.MaterialId='{1}'
)as t left join (select a.PreparationNoteId,a.MaterialId,SUM(a.PackNums) as Nums from PB_TransportBillDetail as a
 where a.ParentId='{2}' and a.PreparationNoteId='{0}' and a.MaterialId='{1}' and a.PackId='' and a.JobId='' GROUP BY a.PreparationNoteId,a.MaterialId) as c
 on t.Id=c.MaterialId and t.PickMainId=c.PreparationNoteId";
                string sqlMain = string.Format(sql, stockId, materialId, BillId);
                List<PickListMaterialDTO> listdata = await Db.GetListBySqlAsync<PickListMaterialDTO>(sqlMain);
                if (!listdata.FirstOrDefault().PickMainId.IsNullOrEmpty())
                {
                    listdata.FirstOrDefault().TrueOrFalse = true;
                    return listdata.FirstOrDefault();
                }
                else
                {
                    sql = @" select '' as PickMainId,Id,`Name`,`Code`,Spec,0 as Nums from pb_material where Id='" + materialId + "'";
                    listdata = await Db.GetListBySqlAsync<PickListMaterialDTO>(sql);
                    listdata.FirstOrDefault().TrueOrFalse = false;
                    return listdata.FirstOrDefault();
                }
                //if (listdata.FirstOrDefault().IsNullOrEmpty())
                //{
                //    throw new BusException("请检查物料与备货单已备物料是否匹配");
                //}
                //if (listdata.FirstOrDefault().Id.IsNullOrEmpty())
                //{
                //    throw new BusException("请检查物料与备货单已备物料是否匹配");
                //}
               
            }
            else
            {
                throw new BusException("请扫描正确的物料二维码");
            }
        }

        /// <summary>
        /// 完成装车
        /// </summary>
        /// <param name="billId">车id</param>
        /// 修改装车时间改为数据库时间    2022-02-21    赵锦涛
        /// <returns></returns>
        public async Task CompleteTransportBillAsync(string billId)
        {
            string sqlMain = @"update PB_TransportBill set LoadingEndTime=NOW(),State=2 where id='" + billId + "'";
            await ExecuteSqlAsync(sqlMain);
        }

        /// <summary>
        /// 完成装车并保存装车图片
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [Transactional]
        public async Task SubmitBillImgsAsync(PB_TransportBillImgDTO data)
        {
            string sqlMain = @"update PB_TransportBill set LoadingEndTime=NOW(),State=2 where id='" + data.billId + "'";
            await ExecuteSqlAsync(sqlMain);
            Base_User bdata = await Db.GetIQueryable<Base_User>().Where(x => x.Id == _operator.UserId).FirstOrDefaultAsync();
            List<PB_TransportBillImg> list = new List<PB_TransportBillImg>();
            foreach (var item in data.listdata)
            {
                PB_TransportBillImg pbdata = new PB_TransportBillImg();
                pbdata.Id = IdHelper.GetId();
                pbdata.BillId = data.billId;
                pbdata.Img = item;
                pbdata.CreatorId = _operator.UserId;
                pbdata.CreatorName = bdata.RealName;
                pbdata.CreateTime = DateTime.Now;
                pbdata.Deleted = false;
                list.Add(pbdata);
            }
            await Db.InsertAsync<PB_TransportBillImg>(list);
            ///获取本次装车的项目和装车数量
            Expression<Func<PB_TransportBillGroup, PB_DeliveryNotice, PB_TransportBillDetail, PB_TransportBillGroupProjectDataDTO>> select = (a, b, c) => new PB_TransportBillGroupProjectDataDTO
            {
                ProjectId = b.ProjectId,
                ProjectName = b.ProjectName,
                PackNums = c.PackNums
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in Db.GetIQueryable<PB_TransportBillGroup>().AsExpandable()
                    join b in Db.GetIQueryable<PB_DeliveryNotice>() on a.DeliveryNoticeId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    join c in Db.GetIQueryable<PB_TransportBillDetail>() on a.ParentId equals c.ParentId into ac
                    from c in ac.DefaultIfEmpty()
                    select @select.Invoke(a, b, c);
            var listdata = await q.Where(x => x.ParentId == data.billId).ToListAsync();
            var grouplist = listdata.GroupBy(x => new { x.ProjectId, x.ProjectName }).Select(x => new
            {
                ProjectId = x.Key.ProjectId,
                ProjectName = x.Key.ProjectName,
                PackNums = x.Sum(i => i.PackNums)
            }).ToList();
            //添加项目装车记录
            List<PB_ProjectProcess> projectlist = new List<PB_ProjectProcess>();
            foreach (var item in grouplist)
            {
                PB_ProjectProcess prdata = new PB_ProjectProcess();
                prdata.Id = IdHelper.GetId();
                prdata.ProjectId = item.ProjectId;
                prdata.ProjectName = item.ProjectName;
                prdata.BuildingnumberId = "";
                prdata.BuildingnumberName = "";
                prdata.ProcessType = "LoadBill";
                prdata.Remarks = item.PackNums.ToString() + "件";
                prdata.CreatorId = _operator.UserId;
                prdata.CreatorRealName = bdata.RealName;
                prdata.CreateTime = DateTime.Now;
                prdata.Deleted = false;
                prdata.OrderId = data.billId;
                projectlist.Add(prdata);
            }
            await Db.InsertAsync<PB_ProjectProcess>(projectlist);
        }


        private async Task<List<TheoreticalWeight>> getTheoreticalWeightAsync(string id)
        {

            StringBuilder sql = new StringBuilder();

            sql.AppendLine("SELECT");
            sql.AppendLine("IFNULL(SUM(e.PackNums * g.Weight), 0)   AS TheoreticalWeights,");
            sql.AppendLine("a.Id");
            sql.AppendLine("FROM");
            sql.AppendLine("PB_TransportBill AS a");
            sql.AppendLine("LEFT JOIN PB_DeliveryNotice AS b ON a.DeliveryNoticeId = b.Id");
            sql.AppendLine("LEFT JOIN PB_Vehicle AS c ON a.Vehicle = c.Id");
            sql.AppendLine("LEFT JOIN PB_TransportBillDetail AS e ON a.Id = e.ParentId");
            sql.AppendLine("LEFT JOIN PB_Material AS g ON e.MaterialId = g.Id");
            sql.AppendLine("LEFT JOIN PB_PackList AS o ON e.PackId = o.Id  AND o.MaterialId = g.Id");
            sql.AppendLine("WHERE");
            sql.AppendLine("a.id = '" + id + "'");
            sql.AppendLine("GROUP BY");
            sql.AppendLine("a.Id");
            return await Db.GetListBySqlAsync<TheoreticalWeight>(sql.ToString());
        }

        /// <summary>
        /// 审核车辆获取车辆详细信息
        /// </summary>
        /// <param name="id">车id</param>
        /// <returns></returns>
        public async Task<PB_TransportBillDataDTO> GetBillDataAsync(string id)
        {
            Expression<Func<PB_TransportBill, PB_DeliveryNotice, PB_Vehicle, PB_TransportBillDetail, PB_PackList, PB_Material, PB_TransportBillMXDTO>> select = (a, b, c, d, e, f) => new PB_TransportBillMXDTO
            {
                PlateNO = c.PlateNO,
                SupplierId = c.SupplierId,
                ProjectName = b.ProjectName,
                TheoreticalWeight = e.Nums * (f.Width == null ? 0 : f.Width),
            };
            select = select.BuildExtendSelectExpre();
            var qt = from a in Db.GetIQueryable<PB_TransportBill>().AsExpandable()
                     join b in Db.GetIQueryable<PB_DeliveryNotice>() on a.DeliveryNoticeId equals b.Id into ab
                     from b in ab.DefaultIfEmpty()
                     join c in Db.GetIQueryable<PB_Vehicle>() on a.Vehicle equals c.Id into ac
                     from c in ac.DefaultIfEmpty()
                     join d in Db.GetIQueryable<PB_TransportBillDetail>() on a.Id equals d.ParentId into ad
                     from d in ad.DefaultIfEmpty()
                     join e in Db.GetIQueryable<PB_PackList>() on d.PackId equals e.Id into ae
                     from e in ae.DefaultIfEmpty()
                     join f in Db.GetIQueryable<PB_Material>() on e.MaterialId equals f.Id into af
                     from f in af.DefaultIfEmpty()
                     select @select.Invoke(a, b, c, d, e, f);
            var q = await qt.Where(x => x.Id == id).FirstOrDefaultAsync();
            if (q != null)
            {
                var Weight = await getTheoreticalWeightAsync(q.Id);

                PB_TransportBillDataDTO pbdata = new PB_TransportBillDataDTO();


                pbdata.PB_TransportBill = q;
                pbdata.PB_TransportBill.TheoreticalWeight = Convert.ToDouble(Weight[0].TheoreticalWeights);
                var qdata = await Db.GetDataTableWithSqlAsync("select * from _ViewBillDetailById  where BilId='"+id+"'");
                List<TransportBillDetail> listdata = new List<TransportBillDetail>();
                foreach (DataRow dr in qdata.Rows)
                {
                    TransportBillDetail tbdata = new TransportBillDetail();
                    tbdata.MaterialCode = dr["MaterialCode"].ToString();
                    tbdata.MaterialName = dr["MaterialName"].ToString();
                    tbdata.DesignQuantity = Convert.ToDouble(dr["DesignQuantity"]);
                    tbdata.StockQuantity = Convert.ToDouble(dr["StockQuantity"]);
                    tbdata.LoadingQuantity = Convert.ToDouble(dr["LoadingQuantity"]);
                    listdata.Add(tbdata);
                }
                List<PB_Project> PB_Projects = await Db.GetListBySqlAsync<PB_Project>("SELECT b.Abstract 'Name'FROM  PB_TransportBillGroup AS a JOIN PB_DeliveryNotice AS b ON a.DeliveryNoticeId = b.Id JOIN PB_Project AS c ON b.ProjectId = c.Id WHERE a.ParentId = '" + id + "'");

                pbdata.TransportBillDetail = listdata;
                pbdata.ProjectList = PB_Projects;
                pbdata.TransportBillImg = await Db.GetIQueryable<PB_TransportBillImg>().Where(x => x.BillId == q.Id).ToListAsync();
                return pbdata;
            }
            else
            {
                throw new BusException("车辆暂无数据");
            }
        }

        /// <summary>
        /// 车俩审核
        /// </summary>
        /// <param name="id">车Id</param>
        /// 车辆审核只是对车辆的状态的修改,回写设计清单数量改到现场验收扫码卸车时回写  2022-02-18   赵锦涛
        /// <returns></returns>

        public async Task SubmitBillDataAsync(string id, double Threshold)
        {




            //var BillData =await Db.GetIQueryable<PB_TransportBill>().Where(m=>m.Id==id).FirstOrDefaultAsync();
            //if (BillData.State==2) { 


            //var Weight = await getTheoreticalWeightAsync(id);
            //    int state = 0;
            //    double? Chazhi = BillData.NetloadNumber-(Convert.ToDouble(Weight[0].TheoreticalWeights)/1000);
            //double? Yuzhi = Convert.ToDouble(Weight[0].TheoreticalWeights)/1000 * (Threshold / 100);
            //    string num = "";
            //if (Chazhi> Yuzhi) {
            //        num = Chazhi.ToString();
            //    }
            //if (Chazhi < -Yuzhi)
            //  {
            //        num = Chazhi.ToString();
            //    }

            //    if (!num.IsNullOrEmpty()) {
            //        state = 1;
            //}
            // await ExecuteSqlAsync($"update PB_TransportBill set State=3,WeightErrRemarks='货运差值过大("+num+ "T)',WeightErrStatus="+state+"  where Id='" + id + "'");

            //}
            await ExecuteSqlAsync("update PB_TransportBill set State=3  where Id='" + id + "'");
        }

        /// <summary>
        /// 验收获取车辆明细信息
        /// </summary>
        /// <param name="billqrcode">派车单二维码</param>
        /// <returns></returns>
        public async Task<PB_TransportBillDTO> GetBillListDataAsync(string billqrcode)
        {
            var q = await Db.GetIQueryable<PB_TransportBill>().Where(x => x.Id == billqrcode.Split(',')[1].ToString()).FirstOrDefaultAsync();
            if (q != null)
            {
                if (q.State == 5)
                {
                    throw new BusException("已验收");
                }
                else if (q.BillType == "Outsourcing_I" && q.State == 1)
                {
                    var cedata = await Db.GetIQueryable<PB_Vehicle>().Where(x => x.Id == q.Vehicle).FirstOrDefaultAsync();
                    PB_TransportBillDTO pbdata = new PB_TransportBillDTO();
                    pbdata.Id = q.Id;
                    pbdata.CreateTime = q.CreateTime;
                    pbdata.CreatorId = q.CreatorId;
                    pbdata.Deleted = q.Deleted;
                    pbdata.Vehicle = q.Vehicle;
                    pbdata.SendTime = q.SendTime;
                    pbdata.IntoTime = q.IntoTime;
                    pbdata.DeliveryTime = q.DeliveryTime;
                    pbdata.Tunnage = q.Tunnage;
                    pbdata.DocumentMaker = q.DocumentMaker;
                    pbdata.EmptyNumber = q.EmptyNumber;
                    pbdata.EmptyTime = q.EmptyTime;
                    pbdata.NetloadNumber = q.NetloadNumber;
                    pbdata.RoughweightNumber = q.RoughweightNumber;
                    pbdata.RoughweightTime = q.RoughweightTime;
                    pbdata.WeighingPeople = q.WeighingPeople;
                    pbdata.DepartureTime = q.DepartureTime;
                    pbdata.State = q.State;
                    pbdata.DriverName = q.DriverName;
                    pbdata.Iphone = q.Iphone;
                    pbdata.PlateNO = cedata.PlateNO;
                    pbdata.VehicleLicense = q.VehicleLicense;
                    pbdata.DrivingLicense = q.DrivingLicense;
                    pbdata.Estimatedweight = q.Estimatedweight;
                    pbdata.EnteringPlantMan = q.EnteringPlantMan;
                    pbdata.ExFactoryMan = q.ExFactoryMan;
                    pbdata.QrCode = q.QrCode;
                    Expression<Func<PB_TransportBillDetail, PB_PackList, PB_TransportBillDetailDataDTO>> select = (a, b) => new PB_TransportBillDetailDataDTO
                    {
                        PackName = b.BoxName
                    };
                    select = select.BuildExtendSelectExpre();
                    var qdata = from a in Db.GetIQueryable<PB_TransportBillDetail>().AsExpandable()
                                join b in Db.GetIQueryable<PB_PackList>() on a.PackId equals b.Id into ab
                                from b in ab.DefaultIfEmpty()
                                select @select.Invoke(a, b);
                    qdata = qdata.Where(x => x.ParentId == q.Id && x.Status == 1).OrderByDescending(x => x.CreateTime);
                    pbdata.TransportBillDetail = await qdata.ToListAsync();
                    pbdata.TransportBillImg = await Db.GetIQueryable<PB_TransportBillImg>().Where(x => x.BillId == q.Id).ToListAsync();
                    return pbdata;
                }
                else
                {
                    if (q.State == 4)
                    {
                        var cedata = await Db.GetIQueryable<PB_Vehicle>().Where(x => x.Id == q.Vehicle).FirstOrDefaultAsync();
                        PB_TransportBillDTO pbdata = new PB_TransportBillDTO();
                        pbdata.Id = q.Id;
                        pbdata.CreateTime = q.CreateTime;
                        pbdata.CreatorId = q.CreatorId;
                        pbdata.Deleted = q.Deleted;
                        pbdata.Vehicle = q.Vehicle;
                        pbdata.SendTime = q.SendTime;
                        pbdata.IntoTime = q.IntoTime;
                        pbdata.DeliveryTime = q.DeliveryTime;
                        pbdata.Tunnage = q.Tunnage;
                        pbdata.DocumentMaker = q.DocumentMaker;
                        pbdata.EmptyNumber = q.EmptyNumber;
                        pbdata.EmptyTime = q.EmptyTime;
                        pbdata.NetloadNumber = q.NetloadNumber;
                        pbdata.RoughweightNumber = q.RoughweightNumber;
                        pbdata.RoughweightTime = q.RoughweightTime;
                        pbdata.WeighingPeople = q.WeighingPeople;
                        pbdata.DepartureTime = q.DepartureTime;
                        pbdata.State = q.State;
                        pbdata.DriverName = q.DriverName;
                        pbdata.Iphone = q.Iphone;
                        pbdata.PlateNO = cedata.PlateNO;
                        pbdata.VehicleLicense = q.VehicleLicense;
                        pbdata.DrivingLicense = q.DrivingLicense;
                        pbdata.Estimatedweight = q.Estimatedweight;
                        pbdata.EnteringPlantMan = q.EnteringPlantMan;
                        pbdata.ExFactoryMan = q.ExFactoryMan;
                        pbdata.QrCode = q.QrCode;
                        Expression<Func<PB_TransportBillDetail, PB_PackList, PB_TransportBillDetailDataDTO>> select = (a, b) => new PB_TransportBillDetailDataDTO
                        {
                            PackName = b.BoxName
                        };
                        select = select.BuildExtendSelectExpre();
                        var qdata = from a in Db.GetIQueryable<PB_TransportBillDetail>().AsExpandable()
                                    join b in Db.GetIQueryable<PB_PackList>() on a.PackId equals b.Id into ab
                                    from b in ab.DefaultIfEmpty()
                                    select @select.Invoke(a, b);
                        qdata = qdata.Where(x => x.ParentId == q.Id && x.Status == 1).OrderByDescending(x => x.CreateTime);
                        pbdata.TransportBillDetail = await qdata.ToListAsync();
                        pbdata.TransportBillImg = await Db.GetIQueryable<PB_TransportBillImg>().Where(x => x.BillId == q.Id).ToListAsync();

                        // 获取派车单对应的项目信息
                        string sqlMain = @"select b.Id as DeliveryNoticeId,b.ProjectId,b.ProjectName from PB_TransportBillGroup as a join PB_DeliveryNotice as b on a.DeliveryNoticeId=b.Id where a.ParentId='" + q.Id + "'group by b.Id,b.ProjectId,b.ProjectName";
                        pbdata.ProjectList = await Db.GetListBySqlAsync<BillProjectDTO>(sqlMain);
                        return pbdata;
                    }
                    else
                    {
                        throw new BusException("暂无验收车辆信息");
                    }
                }
            }
            else
            {
                throw new BusException("请核对车辆信息");
            }
        }

        /// <summary>
        /// 获取车辆对应的项目信息
        /// </summary>
        /// <param name="billqrcode">派车单二维码</param>
        /// <returns></returns>
        public async Task<List<BillProjectDTO>> GetBillProjectListAsync(string billqrcode)
        {
            //派车单Id
            string billId = billqrcode.Split(',')?[1].ToString();
            //获取派车单对应的项目信息
            string sqlMain = @"select b.Id as DeliveryNoticeId,b.ProjectId,b.ProjectName from PB_TransportBillGroup as a join PB_DeliveryNotice as b on a.DeliveryNoticeId=b.Id where a.ParentId='" + billId + "'group by b.Id,b.ProjectId,b.ProjectName";
            List<BillProjectDTO> listdata = await Db.GetListBySqlAsync<BillProjectDTO>(sqlMain);
            if (listdata.Count > 0)
            {
                return listdata;
            }
            else
            {
                throw new BusException("暂无数据");
            }
        }
        /// <summary>
        /// 验收卸车扫描包信息
        /// </summary>
        /// <param name="billqrcode">车辆二维码</param>
        /// <param name="packqrcode">包二维码</param>
        /// <returns></returns>
        public async Task UnloadPackDatasAsync(string billqrcode, string packqrcode)
        {
            string billId = billqrcode.Split(',')?[1].ToString();
            string packId = packqrcode.Split(',')?[1].ToString();
            Base_User userdata = await Db.GetIQueryable<Base_User>().Where(x => x.Id == _operator.UserId).FirstOrDefaultAsync();
            PB_TransportBillDetail pbdata = await Db.GetIQueryable<PB_TransportBillDetail>().Where(x => x.ParentId == billId && x.PackId == packId).FirstOrDefaultAsync();
            if (pbdata != null)
            {
                if (pbdata.Status == 1)
                {
                    throw new BusException("包已卸车");
                }
                else
                {
                    ReceivingRemarksDTO rrdata = new ReceivingRemarksDTO
                    {
                        BillDetailId = pbdata.Id,
                        //ProjectId = data.ProjectId,
                        MaterialId = pbdata.MaterialId,
                        ReceivingUserId = _operator.UserId,
                        ReceivingUserName = userdata.RealName,
                        ReceivingTime = DateTime.Now,
                        ReceivingNums = pbdata.PackNums
                    };
                    PB_TransportBillDetail dtdat = new PB_TransportBillDetail
                    {
                        Id = pbdata.Id,
                        Status = 1,
                        ReceiptQuantity = pbdata.PackNums,
                        ReceivingRemarks = rrdata.ToJson(),
                        CreateTime = pbdata.CreateTime
                    };
                    List<string> props = GetFieldList<PB_TransportBillDetail>(dtdat);
                    await Db.UpdateAsync<PB_TransportBillDetail>(dtdat, props);

                    PB_TransportBillDetailList DetailList = new PB_TransportBillDetailList();
                    DetailList.Id = IdHelper.GetId();
                    DetailList.BillId = billId;
                    DetailList.BillDetailId = pbdata.Id;
                    //DetailList.ProjectId = data.ProjectId;
                    DetailList.MaterialId = pbdata.MaterialId;
                    DetailList.ReceivingUserId = _operator.UserId;
                    DetailList.ReceivingUserName = userdata.RealName;
                    DetailList.ReceivingTime = DateTime.Now;
                    DetailList.ReceivingNums = pbdata.PackNums;
                    DetailList.Status = 0;
                    await Db.InsertAsync<PB_TransportBillDetailList>(DetailList);
                    //string sqlMain = @"update PB_TransportBillDetail set `Status`=1 where  ParentId='" + billId + "' and PackId='" + packId + "'";
                    //await ExecuteSqlAsync(sqlMain);
                }
            }
            else
            {
                throw new BusException("请扫描正确的包信息");
            }
        }

        /// <summary>
        /// 验收卸车扫描包信息
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>

        //public async Task UnloadPackDataAsync(BillDetailDTO data)
        //{
        //    //派车单id
        //    string billId = data.billqrcode.Split(',')?[1].ToString();
        //    string packmodel = data.packqrcode.Split(',')?[0].ToString();
        //    string materialId = string.Empty;
        //    string jobid = data.packqrcode.Split(',')?[1].ToString();
        //    string packid = string.Empty;
        //    Base_User userdata = await Db.GetIQueryable<Base_User>().Where(x => x.Id == _operator.UserId).FirstOrDefaultAsync();
        //    Base_LinkType linktypedata = await _opdept.GetLinkType("MaterialCode");
        //    #region 定义请求头
        //    if (linktypedata.Whether == true)
        //    {
        //        if (packmodel == "13")
        //        {
        //            packid = data.packqrcode.Split(',')[1].ToString();
        //        }
        //        else if (packmodel == "14")
        //        {
        //            jobid = data.packqrcode.Split(',')[1].ToString();
        //        }
        //        else if (packmodel == "04")
        //        {
        //            var model = data.packqrcode.Split(',');
        //            if (model.Length > 2)
        //            {
        //                if (model.Length < 4)
        //                {
        //                    throw new BusException("请扫描正确的二维码信息");
        //                }
        //                else
        //                {
        //                    materialId = model?[3].ToString();
        //                }
        //            }
        //            else
        //            {
        //                materialId = model?[1].ToString();
        //            }
        //            //合并重复物料指向新的物料Id
        //            PB_Material materdata = await Db.GetIQueryable<PB_Material>().Where(x => x.Id == materialId).FirstOrDefaultAsync();
        //            if (!materdata.TransferId.IsNullOrEmpty())
        //            {
        //                materialId = materdata.TransferId;
        //            }
        //        }

        //        else
        //        {
        //            //获取请求头
        //            packmodel = data.JobQrCode.Split(',')?[0].ToString();
        //            //获取成品Id
        //            jobid = data.JobQrCode.Split(',')?[1].ToString();
        //            if (!data.packqrcode.IsNullOrEmpty())
        //            {
        //                packid = data.packqrcode.Split(',')?[1].ToString();
        //            }
        //        }
        //    }
        //    #endregion
        //    if (packmodel == "13")
        //    {
        //        string packId = data.packqrcode.Split(',')?[1].ToString();
        //        PB_PackList packdata = await Db.GetIQueryable<PB_PackList>().Where(x => x.Id == packId).FirstOrDefaultAsync();
        //        if (packdata == null)
        //        {
        //            throw new BusException("此包不存在于清单中!");
        //        }
        //        if (packdata.PackageType == 0)
        //        {
        //            PB_TransportBillDetail pbdata = await Db.GetIQueryable<PB_TransportBillDetail>().Where(x => x.ParentId == billId && x.PackId == packId).FirstOrDefaultAsync();

        //            if (pbdata != null)
        //            {

        //                var PB_TransportBillDetailPack = await Db.GetIQueryable<PB_TransportBillDetail>().Where(m => m.PackId == packId).FirstOrDefaultAsync();
        //                if (PB_TransportBillDetailPack.ReceiptQuantity > 0)
        //                {
        //                    throw new BusException("禁止重复扫码!");
        //                }
        //                ReceivingRemarksDTO rrdata = new ReceivingRemarksDTO
        //                {
        //                    BillDetailId = pbdata.Id,
        //                    ProjectId = data.ProjectId,
        //                    MaterialId = pbdata.MaterialId,
        //                    ReceivingUserId = _operator.UserId,
        //                    ReceivingUserName = userdata.RealName,
        //                    ReceivingTime = DateTime.Now,
        //                    ReceivingNums = pbdata.PackNums
        //                };
        //                PB_TransportBillDetail dtdat = new PB_TransportBillDetail
        //                {
        //                    Id = pbdata.Id,
        //                    Status = 1,
        //                    ReceiptQuantity = pbdata.PackNums,
        //                    ReceivingRemarks = rrdata.ToJson(),
        //                    CreateTime = pbdata.CreateTime
        //                };
        //                List<string> props = GetFieldList<PB_TransportBillDetail>(dtdat);
        //                await Db.UpdateAsync<PB_TransportBillDetail>(dtdat, props);

        //                PB_TransportBillDetailList DetailList = new PB_TransportBillDetailList();
        //                DetailList.Id = IdHelper.GetId();
        //                DetailList.BillId = billId;
        //                DetailList.BillDetailId = pbdata.Id;
        //                DetailList.ProjectId = data.ProjectId;
        //                DetailList.MaterialId = pbdata.MaterialId;
        //                DetailList.ReceivingUserId = _operator.UserId;
        //                DetailList.ReceivingUserName = userdata.RealName;
        //                DetailList.ReceivingTime = DateTime.Now;
        //                DetailList.ReceivingNums = pbdata.PackNums;
        //                DetailList.Status = 0;
        //                await Db.InsertAsync<PB_TransportBillDetailList>(DetailList);

        //            }
        //            else
        //            {
        //                throw new BusException("当前清单不包含此包");
        //            }
        //        }
        //        else if (packdata.PackageType == 1)
        //        {
        //            List<PB_TransportBillDetail> pbdata = await Db.GetIQueryable<PB_TransportBillDetail>().Where(x => x.ParentId == billId && x.PackId == packId).ToListAsync();
        //            if (pbdata.Count > 0)
        //            {
        //                List<PB_TransportBillDetailList> listdata = new List<PB_TransportBillDetailList>();
        //                string sqlItem = string.Empty;
        //                foreach (var item in pbdata)
        //                {
        //                    ReceivingRemarksDTO rrdata = new ReceivingRemarksDTO
        //                    {
        //                        BillDetailId = item.Id,
        //                        ProjectId = data.ProjectId,
        //                        MaterialId = item.MaterialId,
        //                        ReceivingUserId = _operator.UserId,
        //                        ReceivingUserName = userdata.RealName,
        //                        ReceivingTime = DateTime.Now,
        //                        ReceivingNums = item.PackNums
        //                    };
        //                    PB_TransportBillDetail dtdat = new PB_TransportBillDetail
        //                    {
        //                        Id = item.Id,
        //                        Status = 1,
        //                        ReceiptQuantity = item.PackNums,
        //                        ReceivingRemarks = rrdata.ToJson(),
        //                        CreateTime = item.CreateTime
        //                    };
        //                    List<string> props = GetFieldList<PB_TransportBillDetail>(dtdat);
        //                    await Db.UpdateAsync<PB_TransportBillDetail>(dtdat, props);
        //                    PB_TransportBillDetailList DetailList = new PB_TransportBillDetailList();
        //                    DetailList.Id = IdHelper.GetId();
        //                    DetailList.BillId = billId;
        //                    DetailList.BillDetailId = item.Id;
        //                    DetailList.ProjectId = data.ProjectId;
        //                    DetailList.MaterialId = item.MaterialId;
        //                    DetailList.ReceivingUserId = _operator.UserId;
        //                    DetailList.ReceivingUserName = userdata.RealName;
        //                    DetailList.ReceivingTime = DateTime.Now;
        //                    DetailList.ReceivingNums = item.PackNums;
        //                    DetailList.Status = 0;
        //                    listdata.Add(DetailList);
        //                }

        //                await Db.InsertAsync<PB_TransportBillDetailList>(listdata);
        //            }
        //        }
        //        else
        //        {
        //            throw new BusException("请扫描正确的包信息");
        //        }
        //    }
        //    else if (packmodel == "14")
        //    {
        //        if (linktypedata.Whether == true)
        //        {

        //            PB_JobBookingQrCode packdata = await Db.GetIQueryable<PB_JobBookingQrCode>().Where(x => x.Id == jobid).FirstOrDefaultAsync();
        //            PB_TransportBillDetail pbdata = await Db.GetIQueryable<PB_TransportBillDetail>().Where(x => x.ParentId == billId && x.JobId == jobid).FirstOrDefaultAsync();
        //            if (pbdata.IsNullOrEmpty())
        //            {
        //                throw new BusException("请检查扫描或输入的码是否是单个成品码");
        //            }
        //            PB_TransportBillDetailList WhetherExistsNull = await Db.GetIQueryable<PB_TransportBillDetailList>().Where(m => m.BillDetailId == pbdata.Id).FirstOrDefaultAsync();
        //            if (WhetherExistsNull != null)
        //            {
        //                throw new BusException("禁止重复扫码");
        //            }
        //            if (pbdata != null)
        //            {
        //                ReceivingRemarksDTO rrdata = new ReceivingRemarksDTO
        //                {
        //                    BillDetailId = pbdata.Id,
        //                    ProjectId = data.ProjectId,
        //                    MaterialId = pbdata.MaterialId,
        //                    ReceivingUserId = _operator.UserId,
        //                    ReceivingUserName = userdata.RealName,
        //                    ReceivingTime = DateTime.Now,
        //                    ReceivingNums = pbdata.PackNums
        //                };
        //                PB_TransportBillDetail dtdat = new PB_TransportBillDetail
        //                {
        //                    Id = pbdata.Id,
        //                    Status = 1,
        //                    ReceiptQuantity = pbdata.PackNums,
        //                    ReceivingRemarks = rrdata.ToJson(),
        //                    CreateTime = pbdata.CreateTime
        //                };
        //                List<string> props = GetFieldList<PB_TransportBillDetail>(dtdat);
        //                await Db.UpdateAsync<PB_TransportBillDetail>(dtdat, props);
        //                PB_TransportBillDetailList DetailList = new PB_TransportBillDetailList();
        //                DetailList.Id = IdHelper.GetId();
        //                DetailList.BillId = billId;
        //                DetailList.BillDetailId = pbdata.Id;
        //                DetailList.ProjectId = data.ProjectId;
        //                DetailList.MaterialId = pbdata.MaterialId;
        //                DetailList.ReceivingUserId = _operator.UserId;
        //                DetailList.ReceivingUserName = userdata.RealName;
        //                DetailList.ReceivingTime = DateTime.Now;
        //                DetailList.ReceivingNums = pbdata.PackNums;
        //                DetailList.Status = 0;
        //                await Db.InsertAsync<PB_TransportBillDetailList>(DetailList);
        //            }


        //        }
        //        else
        //        {
        //            //扫描组装件的单个物料成品
        //            if (packid.IsNullOrEmpty())
        //            {
        //                //查询成品物料信息
        //                PB_JobBookingQrCode jobdata = await Db.GetIQueryable<PB_JobBookingQrCode>().Where(x => x.Id == jobid).FirstOrDefaultAsync();
        //                if (jobdata == null)
        //                {
        //                    throw new BusException("请检查成品信息是否正确");
        //                }
        //                //查询装车单明细物料信息
        //                PB_TransportBillDetail pbdata = await Db.GetIQueryable<PB_TransportBillDetail>().Where(x => x.ParentId == billId && x.PackId == "" && x.MaterialId == jobdata.MaterialId && x.ReceiptQuantity < x.PackNums).FirstOrDefaultAsync();
        //                double? nums = (pbdata.ReceiptQuantity + data.Nums) - pbdata.PackNums;
        //                if (nums <= 0)
        //                {
        //                    ReceivingRemarksDTO rrdata = new ReceivingRemarksDTO
        //                    {

        //                        BillDetailId = pbdata.Id,
        //                        ProjectId = data.ProjectId,
        //                        MaterialId = pbdata.MaterialId,
        //                        ReceivingUserId = _operator.UserId,
        //                        ReceivingUserName = userdata.RealName,
        //                        ReceivingTime = DateTime.Now,
        //                        ReceivingNums = pbdata.ReceiptQuantity + data.Nums
        //                    };

        //                    PB_TransportBillDetail dtdat = new PB_TransportBillDetail
        //                    {
        //                        Id = pbdata.Id,
        //                        Status = 1,
        //                        ReceiptQuantity = pbdata.ReceiptQuantity + data.Nums,
        //                        ReceivingRemarks = rrdata.ToJson(),
        //                        CreateTime = pbdata.CreateTime
        //                    };
        //                    List<string> props = GetFieldList<PB_TransportBillDetail>(dtdat);
        //                    await Db.UpdateAsync<PB_TransportBillDetail>(dtdat, props);
        //                    //单个成品物料收货
        //                    PB_TransportBillDetailList DetailList = new PB_TransportBillDetailList();
        //                    DetailList.Id = IdHelper.GetId();
        //                    DetailList.BillId = billId;
        //                    DetailList.BillDetailId = pbdata.Id;
        //                    DetailList.ProjectId = data.ProjectId;
        //                    DetailList.MaterialId = pbdata.MaterialId;
        //                    DetailList.ReceivingUserId = _operator.UserId;
        //                    DetailList.ReceivingUserName = userdata.RealName;
        //                    DetailList.ReceivingTime = DateTime.Now;
        //                    DetailList.ReceivingNums = data.Nums;
        //                    DetailList.Status = 0;
        //                    await Db.InsertAsync<PB_TransportBillDetailList>(DetailList);
        //                }
        //                else
        //                {

        //                    double? QuantitynotNums = data.Nums;
        //                    double? num = 1;
        //                    while (QuantitynotNums > 0)
        //                    {
        //                        PB_TransportBillDetail pbdata2 = await Db.GetIQueryable<PB_TransportBillDetail>().Where(x => x.ParentId == billId && x.PackId == "" && x.MaterialId == jobdata.MaterialId && x.ReceiptQuantity < x.PackNums).FirstOrDefaultAsync();
        //                        if (QuantitynotNums >= (pbdata2.PackNums - pbdata2.ReceiptQuantity))
        //                        {

        //                            QuantitynotNums = QuantitynotNums - (pbdata2.PackNums - pbdata2.ReceiptQuantity);
        //                            num = pbdata2.PackNums - pbdata2.ReceiptQuantity;
        //                            pbdata2.ReceiptQuantity += num;
        //                        }
        //                        else
        //                        {
        //                            num = QuantitynotNums;
        //                            pbdata2.ReceiptQuantity += num;
        //                            QuantitynotNums = 0;
        //                        }
        //                        ReceivingRemarksDTO rrdata = new ReceivingRemarksDTO
        //                        {

        //                            BillDetailId = pbdata2.Id,
        //                            ProjectId = data.ProjectId,
        //                            MaterialId = pbdata2.MaterialId,
        //                            ReceivingUserId = _operator.UserId,
        //                            ReceivingUserName = userdata.RealName,
        //                            ReceivingTime = DateTime.Now,
        //                            ReceivingNums = pbdata2.ReceiptQuantity
        //                        };

        //                        PB_TransportBillDetail dtdat = new PB_TransportBillDetail
        //                        {
        //                            Id = pbdata2.Id,
        //                            Status = 1,
        //                            ReceiptQuantity = pbdata2.ReceiptQuantity,
        //                            ReceivingRemarks = rrdata.ToJson(),
        //                            CreateTime = pbdata2.CreateTime
        //                        };
        //                        List<string> props = GetFieldList<PB_TransportBillDetail>(dtdat);
        //                        await Db.UpdateAsync<PB_TransportBillDetail>(dtdat, props);
        //                        //单个成品物料收货
        //                        PB_TransportBillDetailList DetailList = new PB_TransportBillDetailList();
        //                        DetailList.Id = IdHelper.GetId();
        //                        DetailList.BillId = billId;
        //                        DetailList.BillDetailId = pbdata2.Id;
        //                        DetailList.ProjectId = data.ProjectId;
        //                        DetailList.MaterialId = pbdata2.MaterialId;
        //                        DetailList.ReceivingUserId = _operator.UserId;
        //                        DetailList.ReceivingUserName = userdata.RealName;
        //                        DetailList.ReceivingTime = DateTime.Now;
        //                        DetailList.ReceivingNums = num;
        //                        DetailList.Status = 0;
        //                        await Db.InsertAsync<PB_TransportBillDetailList>(DetailList);
        //                    }

        //                }









        //            }
        //            else
        //            {
        //                //查询成品物料信息
        //                PB_JobBookingQrCode jobdata = await Db.GetIQueryable<PB_JobBookingQrCode>().Where(x => x.Id == jobid).FirstOrDefaultAsync();
        //                if (jobdata == null)
        //                {
        //                    throw new BusException("请检查成品信息是否正确");
        //                }
        //                //查询装车单明细物料信息
        //                PB_TransportBillDetail pbdata = await Db.GetIQueryable<PB_TransportBillDetail>().Where(x => x.ParentId == billId && x.PackId == jobdata.PackId).FirstOrDefaultAsync();

        //                ReceivingRemarksDTO rrdata = new ReceivingRemarksDTO
        //                {

        //                    BillDetailId = pbdata.Id,
        //                    ProjectId = data.ProjectId,
        //                    MaterialId = pbdata.MaterialId,
        //                    ReceivingUserId = _operator.UserId,
        //                    ReceivingUserName = userdata.RealName,
        //                    ReceivingTime = DateTime.Now,
        //                    ReceivingNums = pbdata.ReceiptQuantity + data.Nums
        //                };

        //                PB_TransportBillDetail dtdat = new PB_TransportBillDetail
        //                {
        //                    Id = pbdata.Id,
        //                    Status = 1,
        //                    ReceiptQuantity = pbdata.ReceiptQuantity + data.Nums,
        //                    ReceivingRemarks = rrdata.ToJson(),
        //                    CreateTime = pbdata.CreateTime
        //                };
        //                List<string> props = GetFieldList<PB_TransportBillDetail>(dtdat);
        //                await Db.UpdateAsync<PB_TransportBillDetail>(dtdat, props);
        //                //单个成品物料收货
        //                PB_TransportBillDetailList DetailList = new PB_TransportBillDetailList();
        //                DetailList.Id = IdHelper.GetId();
        //                DetailList.BillId = billId;
        //                DetailList.BillDetailId = pbdata.Id;
        //                DetailList.ProjectId = data.ProjectId;
        //                DetailList.MaterialId = pbdata.MaterialId;
        //                DetailList.ReceivingUserId = _operator.UserId;
        //                DetailList.ReceivingUserName = userdata.RealName;
        //                DetailList.ReceivingTime = DateTime.Now;
        //                DetailList.ReceivingNums = data.Nums;
        //                DetailList.Status = 0;
        //                await Db.InsertAsync<PB_TransportBillDetailList>(DetailList);
        //            }
        //        }
        //    }
        //    else if (packmodel == "04")
        //    {
        //        string MaterialId = string.Empty;
        //        var model = data.packqrcode.Split(',');
        //        if (model.Length > 2)
        //        {
        //            MaterialId = model?[3].ToString();
        //        }
        //        else
        //        {
        //            MaterialId = model?[1].ToString();
        //        }

        //        List<PB_TransportBillDetail> pbdata = await Db.GetIQueryable<PB_TransportBillDetail>().Where(x => x.ParentId == billId && x.MaterialId == MaterialId && x.PackId == "").ToListAsync();
        //        if (pbdata.Count > 0)
        //        {
        //            double? maternums = data.Nums;
        //            List<PB_TransportBillDetailList> listdata = new List<PB_TransportBillDetailList>();
        //            foreach (var item in pbdata)
        //            {
        //                if (maternums > 0)
        //                {
        //                    if (item.ReceivingRemarks.IsNullOrEmpty())
        //                    {
        //                        List<ReceivingRemarksDTO> listrece = new List<ReceivingRemarksDTO>();
        //                        if (maternums <= item.PackNums)
        //                        {
        //                            PB_Material materdata = await Db.GetIQueryable<PB_Material>().Where(x => x.Id == item.MaterialId).FirstOrDefaultAsync();
        //                            if (!materdata.TransferId.IsNullOrEmpty())
        //                            {
        //                                item.MaterialId = materdata.TransferId;
        //                            }
        //                            ReceivingRemarksDTO rrdata = new ReceivingRemarksDTO
        //                            {

        //                                BillDetailId = item.Id,
        //                                ProjectId = data.ProjectId,
        //                                MaterialId = item.MaterialId,
        //                                ReceivingUserId = _operator.UserId,
        //                                ReceivingUserName = userdata.RealName,
        //                                ReceivingTime = DateTime.Now,
        //                                ReceivingNums = maternums
        //                            };
        //                            listrece.Add(rrdata);
        //                            PB_TransportBillDetail dtdat = new PB_TransportBillDetail
        //                            {
        //                                Id = item.Id,
        //                                Status = 1,
        //                                ReceiptQuantity = maternums,
        //                                ReceivingRemarks = listrece.ToJson(),
        //                                CreateTime = item.CreateTime
        //                            };
        //                            List<string> props = GetFieldList<PB_TransportBillDetail>(dtdat);
        //                            await Db.UpdateAsync<PB_TransportBillDetail>(dtdat, props);
        //                            PB_TransportBillDetailList DetailList = new PB_TransportBillDetailList();
        //                            DetailList.Id = IdHelper.GetId();

        //                            DetailList.BillId = billId;
        //                            DetailList.BillDetailId = item.Id;
        //                            DetailList.ProjectId = data.ProjectId;
        //                            DetailList.MaterialId = item.MaterialId;
        //                            DetailList.ReceivingUserId = _operator.UserId;
        //                            DetailList.ReceivingUserName = userdata.RealName;
        //                            DetailList.ReceivingTime = DateTime.Now;
        //                            DetailList.ReceivingNums = data.Nums;
        //                            DetailList.Status = 0;
        //                            listdata.Add(DetailList);

        //                        }
        //                        else
        //                        {
        //                            ReceivingRemarksDTO rrdata = new ReceivingRemarksDTO
        //                            {
        //                                BillDetailId = item.Id,
        //                                ProjectId = data.ProjectId,
        //                                MaterialId = item.MaterialId,
        //                                ReceivingUserId = _operator.UserId,
        //                                ReceivingUserName = userdata.RealName,
        //                                ReceivingTime = DateTime.Now,
        //                                ReceivingNums = item.PackNums
        //                            };
        //                            listrece.Add(rrdata);
        //                            PB_TransportBillDetail dtdat = new PB_TransportBillDetail
        //                            {
        //                                Id = item.Id,
        //                                Status = 1,
        //                                ReceiptQuantity = item.PackNums,
        //                                ReceivingRemarks = item.PackNums.ToString(),
        //                                CreateTime = item.CreateTime
        //                            };
        //                            List<string> props = GetFieldList<PB_TransportBillDetail>(dtdat);
        //                            await Db.UpdateAsync<PB_TransportBillDetail>(dtdat, props);
        //                            PB_TransportBillDetailList DetailList = new PB_TransportBillDetailList();
        //                            PB_Material materdata = await Db.GetIQueryable<PB_Material>().Where(x => x.Id == item.MaterialId).FirstOrDefaultAsync();
        //                            if (!materdata.TransferId.IsNullOrEmpty())
        //                            {
        //                                item.MaterialId = materdata.TransferId;
        //                            }
        //                            DetailList.Id = IdHelper.GetId();
        //                            DetailList.BillId = billId;
        //                            DetailList.BillDetailId = item.Id;
        //                            DetailList.ProjectId = data.ProjectId;
        //                            DetailList.MaterialId = item.MaterialId;
        //                            DetailList.ReceivingUserId = _operator.UserId;
        //                            DetailList.ReceivingUserName = userdata.RealName;
        //                            DetailList.ReceivingTime = DateTime.Now;
        //                            DetailList.ReceivingNums = data.Nums;
        //                            DetailList.Status = 0;
        //                            listdata.Add(DetailList);

        //                        }
        //                    }
        //                    else
        //                    {
        //                        PB_Material materdata = await Db.GetIQueryable<PB_Material>().Where(x => x.Id == item.MaterialId).FirstOrDefaultAsync();
        //                        if (!materdata.TransferId.IsNullOrEmpty())
        //                        {
        //                            item.MaterialId = materdata.TransferId;
        //                        }
        //                        List<ReceivingRemarksDTO> listrece = new List<ReceivingRemarksDTO>();

        //                        double? recnum = item.PackNums - item.ReceiptQuantity;
        //                        if (maternums <= recnum)
        //                        {


        //                            PB_TransportBillDetail dtdat = new PB_TransportBillDetail
        //                            {
        //                                Id = item.Id,
        //                                Status = 1,
        //                                ReceiptQuantity = item.ReceiptQuantity + maternums,
        //                                ReceivingRemarks = "",
        //                                CreateTime = item.CreateTime
        //                            };
        //                            List<string> props = GetFieldList<PB_TransportBillDetail>(dtdat);
        //                            await Db.UpdateAsync<PB_TransportBillDetail>(dtdat, props);
        //                            PB_TransportBillDetailList DetailList = new PB_TransportBillDetailList();

        //                            DetailList.Id = IdHelper.GetId();
        //                            DetailList.BillId = billId;
        //                            DetailList.BillDetailId = item.Id;
        //                            DetailList.ProjectId = data.ProjectId;
        //                            DetailList.MaterialId = item.MaterialId;
        //                            DetailList.ReceivingUserId = _operator.UserId;
        //                            DetailList.ReceivingUserName = userdata.RealName;
        //                            DetailList.ReceivingTime = DateTime.Now;
        //                            DetailList.ReceivingNums = data.Nums;
        //                            DetailList.Status = 0;
        //                            listdata.Add(DetailList);


        //                        }
        //                        else
        //                        {

        //                            ReceivingRemarksDTO rrdata = new ReceivingRemarksDTO
        //                            {
        //                                BillDetailId = item.Id,
        //                                ProjectId = data.ProjectId,
        //                                MaterialId = item.MaterialId,
        //                                ReceivingUserId = _operator.UserId,
        //                                ReceivingUserName = userdata.RealName,
        //                                ReceivingTime = DateTime.Now,
        //                                ReceivingNums = item.PackNums
        //                            };
        //                            listrece.Add(rrdata);
        //                            PB_TransportBillDetail dtdat = new PB_TransportBillDetail
        //                            {
        //                                Id = item.Id,
        //                                Status = 1,
        //                                ReceiptQuantity = item.ReceiptQuantity + recnum,
        //                                ReceivingRemarks = (item.ReceiptQuantity + recnum).ToString(),
        //                                CreateTime = item.CreateTime
        //                            };
        //                            List<string> props = GetFieldList<PB_TransportBillDetail>(dtdat);
        //                            await Db.UpdateAsync<PB_TransportBillDetail>(dtdat, props);
        //                            PB_TransportBillDetailList DetailList = new PB_TransportBillDetailList();
        //                            DetailList.Id = IdHelper.GetId();
        //                            DetailList.BillId = billId;
        //                            DetailList.BillDetailId = item.Id;
        //                            DetailList.ProjectId = data.ProjectId;
        //                            DetailList.MaterialId = item.MaterialId;
        //                            DetailList.ReceivingUserId = _operator.UserId;
        //                            DetailList.ReceivingUserName = userdata.RealName;
        //                            DetailList.ReceivingTime = DateTime.Now;
        //                            DetailList.ReceivingNums = data.Nums;
        //                            DetailList.Status = 0;
        //                            listdata.Add(DetailList);

        //                        }
        //                    }
        //                }
        //                else
        //                {
        //                    continue;
        //                }
        //            }
        //            //await ExecuteSqlAsync(sqlItem);
        //            await Db.InsertAsync<PB_TransportBillDetailList>(listdata);
        //        }
        //        else
        //        {
        //            throw new BusException("请检查扫描或输入的码是否是单件物料码");
        //        }
        //    }
        //}


        /// <summary>
        /// 验收扫描单个物料
        /// </summary>
        /// <param name="billId">派车单Id</param>
        /// <param name="qrcode">单个物料二维码</param>
        /// <returns></returns>
        public async Task<TransportBillDetailMaterialDTO> GetReceMaterialDataAsync(string billId, string qrcode)
        {
            string MaterialId = qrcode.Split(',')[1].ToString();
            Expression<Func<PB_TransportBillDetail, PB_Material, TransportBillDetailMaterialDTO>> select = (a, b) => new TransportBillDetailMaterialDTO
            {
                ParentId = a.ParentId,
                MaterialId = a.MaterialId,
                Code = b.Code,
                Name = b.Name,
                Spec = b.Spec,
                PackId = a.PackId,
                Nums = a.PackNums - a.ReceiptQuantity
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in Db.GetIQueryable<PB_TransportBillDetail>().AsExpandable()
                    join b in Db.GetIQueryable<PB_Material>() on a.MaterialId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    select @select.Invoke(a, b);
            var detaildata = await q.Where(x => x.ParentId == billId && x.MaterialId == MaterialId && x.PackId == "").ToListAsync();
            var data = detaildata.GroupBy(x => new { x.ParentId, x.MaterialId, x.Code, x.Name, x.Spec }).Select(x => new
            {
                ParentId = x.Key.ParentId,
                MaterialId = x.Key.MaterialId,
                Code = x.Key.Code,
                Name = x.Key.Name,
                Spec = x.Key.Spec,
                Nums = x.Sum(i => i.Nums)
            }).FirstOrDefault();
            if (!data.IsNullOrEmpty())
            {
                TransportBillDetailMaterialDTO BillDetail = new TransportBillDetailMaterialDTO();
                BillDetail.ParentId = data.ParentId;
                BillDetail.MaterialId = data.MaterialId;
                BillDetail.Code = data.Code;
                BillDetail.Name = data.Name;
                BillDetail.Spec = data.Spec;
                BillDetail.Nums = data.Nums;
                return BillDetail;
            }
            else {
                TransportBillDetailMaterialDTO BillDetail = new TransportBillDetailMaterialDTO();
                BillDetail.ParentId = billId;
                var materdata =await Db.GetIQueryable<PB_Material>().Where(m=>m.Id== MaterialId).FirstOrDefaultAsync();
                BillDetail.MaterialId = materdata.Id;
                BillDetail.Code = materdata.Code;
                BillDetail.Name = materdata.Name;
                BillDetail.Spec = materdata.Spec;
                BillDetail.Nums =0;
                return BillDetail;
            }

            return null;
        }


        /// <summary>
        /// 现场验收明细信息
        /// </summary>
        /// <param name="billqrcode">派车单二维码</param>
        /// <param name="ProjectId">项目Id</param>
        /// <returns></returns>
//public async Task<PB_TransportBillDataDetailDTO> GetBillReceDetailDataAsync(string billqrcode, string ProjectId, string BudingId)
//        {
//            string billId = billqrcode.Split(',')[1].ToString();
//            Expression<Func<PB_TransportBill, PB_Vehicle, PB_TransportBillDataDetailDTO>> selectdata = (a, b) => new PB_TransportBillDataDetailDTO
//            {
//                PlateName = b.PlateNO
//            };
//            selectdata = selectdata.BuildExtendSelectExpre();
//            var q = from a in Db.GetIQueryable<PB_TransportBill>().AsExpandable()
//                    join b in Db.GetIQueryable<PB_Vehicle>() on a.Vehicle equals b.Id into ab
//                    from b in ab.DefaultIfEmpty()
//                    select @selectdata.Invoke(a, b);
//            var qd = await q.Where(x => x.Id == billId).FirstOrDefaultAsync();
//            if (qd != null)
//            {
//                PB_TransportBillDataDetailDTO pbdata = new PB_TransportBillDataDetailDTO();
//                pbdata.Id = qd.Id;
//                pbdata.CreateTime = qd.CreateTime;
//                pbdata.CreatorId = qd.CreatorId;
//                pbdata.Deleted = qd.Deleted;
//                pbdata.Vehicle = qd.Vehicle;
//                pbdata.SendTime = qd.SendTime;
//                pbdata.IntoTime = qd.IntoTime;
//                pbdata.DeliveryTime = qd.DeliveryTime;
//                pbdata.Tunnage = qd.Tunnage;
//                pbdata.DocumentMaker = qd.DocumentMaker;
//                pbdata.EmptyNumber = qd.EmptyNumber;
//                pbdata.EmptyTime = qd.EmptyTime;
//                pbdata.NetloadNumber = qd.NetloadNumber;
//                pbdata.RoughweightNumber = qd.RoughweightNumber;
//                pbdata.RoughweightTime = qd.RoughweightTime;
//                pbdata.WeighingPeople = qd.WeighingPeople;
//                pbdata.DepartureTime = qd.DepartureTime;
//                pbdata.State = qd.State;
//                pbdata.DriverName = qd.DriverName;
//                pbdata.Iphone = qd.Iphone;
//                pbdata.PlateNO = qd.PlateNO;
//                pbdata.PlateName = qd.PlateName;
//                pbdata.VehicleLicense = qd.VehicleLicense;
//                pbdata.DrivingLicense = qd.DrivingLicense;
//                pbdata.Estimatedweight = qd.Estimatedweight;
//                pbdata.EnteringPlantMan = qd.EnteringPlantMan;
//                pbdata.ExFactoryMan = qd.ExFactoryMan;
//                string sqlMain = @"SELECT *,	ROW_NUMBER() over ( ORDER BY CreateTime DESC ) AS rowsid FROM(SELECT a.Id,a.PackId,a.JobId,a.MaterialId,a.PackNums AS Nums,
//		b.BoxName AS PackName,c.Spec AS MaterialSpec,a.CreateTime,d.ProjectId FROM PB_TransportBillDetail AS a JOIN PB_PackList AS b ON a.PackId = b.Id JOIN PB_Material AS c ON a.MaterialId = c.Id JOIN PB_TransportBillDetailList AS d ON a.Id = d.BillDetailId  AND d.ProjectId = '" + ProjectId + "'  	LEFT JOIN PB_PickUpList AS PickList ON a.PreparationNoteId = PickList.Id 	LEFT JOIN PB_PickUpMain AS Main ON PickList.ParentId = Main.Id LEFT JOIN PB_DeliveryNoticeItem AS Item ON Main.ParentId = Item.Id LEFT JOIN PB_DesignList AS designlist ON Item.DesignId=designlist.Id AND  designlist.BuildingNumberID='" + BudingId + "'	WHERE a.ParentId = '" + billId + "'  	AND b.PackageType = 0 UNION ALL SELECT '' AS Id,PackId,JobId,'' AS MaterialId,SUM( Nums ) AS Nums,PackName,'' AS MaterialSpec,CreateTime,ProjectId FROM(SELECT a.PackId,a.JobId,b.BoxName AS PackName,a.PackNums AS Nums,	DATE_FORMAT( a.CreateTime, '%Y-%m-%d %H:%i:00' ) AS CreateTime,	d.ProjectId FROM	PB_TransportBillDetail AS a	JOIN PB_PackList AS b ON a.PackId =b.Id	JOIN PB_Material AS c ON a.MaterialId = c.Id	JOIN PB_TransportBillDetailList AS d ON a.Id = d.BillDetailId 	AND d.ProjectId = '" + ProjectId + "' 	LEFT JOIN PB_PickUpList AS PickList ON a.PreparationNoteId = PickList.Id	  LEFT JOIN PB_PickUpMain AS Main ON PickList.ParentId = Main.Id	  LEFT JOIN PB_DeliveryNoticeItem AS Item ON Main.ParentId = Item.Id   LEFT JOIN PB_DesignList AS designlist ON Item.DesignId=designlist.Id AND  designlist.BuildingNumberID='" + BudingId + "'	  WHERE	a.ParentId = '" + billId + "'  	AND b.PackageType = 1 	) AS t GROUP BY		PackId,		PackName,		CreateTime,		ProjectId,		JobId UNION ALL	SELECT		a.Id,	a.PackId,		a.JobId,		a.MaterialId,		d.ReceivingNums AS Nums,		b.`Name` AS PackName,		b.Spec AS MaterialSpec,		d.ReceivingTime AS CreateTime,	d.ProjectId 	FROM		PB_TransportBillDetail AS a	JOIN PB_Material AS b ON a.MaterialId = b.Id	JOIN PB_TransportBillDetailList AS d ON a.Id = d.BillDetailId 	AND d.ProjectId = '" + ProjectId + "' 	LEFT JOIN PB_PickUpList AS PickList ON a.PreparationNoteId = PickList.Id	LEFT JOIN PB_PickUpMain AS Main ON PickList.ParentId = Main.Id		LEFT JOIN PB_DeliveryNoticeItem AS Item ON Main.ParentId = Item.Id LEFT JOIN PB_DesignList AS designlist ON Item.DesignId=designlist.Id AND  designlist.BuildingNumberID='" + BudingId + "'  WHERE	a.ParentId = '" + billId + "' AND a.PackId = '' ) AS t";
//                var transportbilldetail = await Db.GetListBySqlAsync<PB_TransportBillDetailListData>(sqlMain);
//                pbdata.TransportBillDetail = transportbilldetail;
//                List<PB_TransportBillDetailList> BillDetailList = await Db.GetIQueryable<PB_TransportBillDetailList>().Where(x => x.BillId == billId && x.ProjectId == ProjectId).ToListAsync();
//                if (BillDetailList.Count > 0)
//                {
//                    var ordata = BillDetailList.GroupBy(x => new { x.Status }).Select(x => new { Status = x.Key.Status }).FirstOrDefault();
//                    if (ordata.Status == 0)
//                    {
//                        pbdata.TrueOrFalse = false;
//                    }
//                    else
//                    {
//                        pbdata.TrueOrFalse = true;
//                    }
//                }
//                else
//                {
//                    pbdata.TrueOrFalse = false;
//                }
//                return pbdata;
//            }
//            else
//            {
//                throw new BusException("请核对车辆信息");
//            }
//        }

        public async Task<PB_TransportBillDataDetailDTO> GetBillReceDetailDataAsync(string billqrcode, string ProjectId, string BudingId)
        {
            string billId = billqrcode.Split(',')[1].ToString();
            Expression<Func<PB_TransportBill, PB_Vehicle, PB_TransportBillDataDetailDTO>> selectdata = (a, b) => new PB_TransportBillDataDetailDTO
            {
                PlateName = b.PlateNO
            };
            selectdata = selectdata.BuildExtendSelectExpre();
            var q = from a in Db.GetIQueryable<PB_TransportBill>().AsExpandable()
                    join b in Db.GetIQueryable<PB_Vehicle>() on a.Vehicle equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    select @selectdata.Invoke(a, b);
            var qd = await q.Where(x => x.Id == billId).FirstOrDefaultAsync();
            if (qd != null)
            {
                PB_TransportBillDataDetailDTO pbdata = new PB_TransportBillDataDetailDTO();
                pbdata.Id = qd.Id;
                pbdata.CreateTime = qd.CreateTime;
                pbdata.CreatorId = qd.CreatorId;
                pbdata.Deleted = qd.Deleted;
                pbdata.Vehicle = qd.Vehicle;
                pbdata.SendTime = qd.SendTime;
                pbdata.IntoTime = qd.IntoTime;
                pbdata.DeliveryTime = qd.DeliveryTime;
                pbdata.Tunnage = qd.Tunnage;
                pbdata.DocumentMaker = qd.DocumentMaker;
                pbdata.EmptyNumber = qd.EmptyNumber;
                pbdata.EmptyTime = qd.EmptyTime;
                pbdata.NetloadNumber = qd.NetloadNumber;
                pbdata.RoughweightNumber = qd.RoughweightNumber;
                pbdata.RoughweightTime = qd.RoughweightTime;
                pbdata.WeighingPeople = qd.WeighingPeople;
                pbdata.DepartureTime = qd.DepartureTime;
                pbdata.State = qd.State;
                pbdata.DriverName = qd.DriverName;
                pbdata.Iphone = qd.Iphone;
                pbdata.PlateNO = qd.PlateNO;
                pbdata.PlateName = qd.PlateName;
                pbdata.VehicleLicense = qd.VehicleLicense;
                pbdata.DrivingLicense = qd.DrivingLicense;
                pbdata.Estimatedweight = qd.Estimatedweight;
                pbdata.EnteringPlantMan = qd.EnteringPlantMan;
                pbdata.ExFactoryMan = qd.ExFactoryMan;
                string sqlMain = @"SELECT vingdetail.Id ,vingdetail.PackId,vingdetail.JobId,vingdetail.MaterialId,vingdetail.Nums,mater.Spec MaterialSpec,mater.`Name` PackName FROM pb_tranrecevingdetail AS vingdetail LEFT JOIN pb_material AS mater ON vingdetail.MaterialId = mater.Id WHERE vingdetail.BillId='"+billId+"'";
                var transportbilldetail = await Db.GetListBySqlAsync<PB_TransportBillDetailListData>(sqlMain);
                pbdata.TransportBillDetail = transportbilldetail;
                return pbdata;
            }
            else
            {
                throw new BusException("请核对车辆信息");
            }
        }

        /// <summary>
        /// 现场验收明细移除
        /// </summary>
        /// <param name="data"></param>
        /// <param name="billId">派车单Id</param>
        /// <param name="ProjectId">项目Id</param>
        /// <returns></returns>
        //public async Task DeleteBillReceDetailDataAsync(PB_TransportBillDetailListData data, string billId, string ProjectId)
        //{
        //    if (!data.PackId.IsNullOrEmpty())
        //    {
        //        string sqlMain = string.Empty;
        //        List<PB_TransportBillDetail> billdeteillist = await Db.GetIQueryable<PB_TransportBillDetail>().Where(x => x.ParentId == billId && x.PackId == data.PackId).ToListAsync();
        //        foreach (var item in billdeteillist)
        //        {
        //            sqlMain += @" update PB_TransportBillDetail set ReceiptQuantity=0,`Status`=0,ReceivingRemarks=NULL where Id='" + item.Id + "';  ";
        //            sqlMain += @" delete from PB_TransportBillDetailList where BillDetailId='" + item.Id + "' AND ProjectId='" + ProjectId + "'; ";
        //        }
        //        await ExecuteSqlAsync(sqlMain);
        //    }
        //    //成品
        //    else if (!data.JobId.IsNullOrEmpty())
        //    {

        //        string sqlMain = string.Empty;
        //        List<PB_TransportBillDetail> billdeteillist = await Db.GetIQueryable<PB_TransportBillDetail>().Where(x => x.ParentId == billId && x.JobId == data.JobId).ToListAsync();
        //        foreach (var item in billdeteillist)
        //        {
        //            sqlMain += @" update PB_TransportBillDetail set ReceiptQuantity=0,`Status`=0,ReceivingRemarks=NULL where Id='" + item.Id + "';  ";
        //            sqlMain += @" delete from PB_TransportBillDetailList where BillDetailId='" + item.Id + "' AND ProjectId='" + ProjectId + "'; ";
        //        }
        //        await ExecuteSqlAsync(sqlMain);
        //    }
        //    else
        //    {
        //        string sqlMain = string.Empty;
        //        PB_TransportBillDetail billdeteil = await Db.GetIQueryable<PB_TransportBillDetail>().Where(x => x.ParentId == billId && x.MaterialId == data.MaterialId && x.PackId == "" && x.JobId == "" && x.Id == data.Id).FirstOrDefaultAsync();
        //        PB_TransportBillDetailList BillDetailList = await Db.GetIQueryable<PB_TransportBillDetailList>().Where(x => x.BillDetailId == billdeteil.Id && x.ProjectId == ProjectId && x.ReceivingNums == data.Nums && x.ReceivingTime == data.CreateTime).FirstOrDefaultAsync();
        //        if (BillDetailList != null)
        //        {
        //            sqlMain += "delete from PB_TransportBillDetailList where Id='" + BillDetailList.Id + "'; ";
        //        }
        //        else
        //        {

        //            sqlMain += "delete from PB_TransportBillDetailList where BillDetailId='" + billdeteil.Id + "' and  MaterialId='" + billdeteil.MaterialId + "' and  ReceivingNums='" + data.Nums + "'; ";
        //        }
        //        PB_TransportBillDetail dtdat = new PB_TransportBillDetail
        //        {
        //            Id = billdeteil.Id,
        //            Status = 1,
        //            ReceiptQuantity = billdeteil.ReceiptQuantity - data.Nums,
        //            CreateTime = billdeteil.CreateTime
        //        };
        //        List<string> props = GetFieldList<PB_TransportBillDetail>(dtdat);
        //        await Db.UpdateAsync<PB_TransportBillDetail>(dtdat, props);
        //        await ExecuteSqlAsync(sqlMain);
        //    }
        //}
        public async Task DeleteBillReceDetailDataAsync(PB_TransportBillDetailListData data, string billId, string ProjectId)
        {
            string sql = "delete from  pb_tranrecevingdetail where Id='"+data.Id+"'";
            await Db.ExecuteSqlAsync(sql);
        }


        /// <summary>
        /// 卸车提交
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task CheckBillDatasAsync(CheckBillDTO data)
        {
            string billId = data.billqrcode.Split(',')?[1].ToString();
            List<PB_TransportBillDetail> listdata = await Db.GetIQueryable<PB_TransportBillDetail>().Where(x => x.ParentId == billId).ToListAsync();
            List<PB_TransportBillDetail> listdatadetile = await Db.GetIQueryable<PB_TransportBillDetail>().Where(x => x.ParentId == billId && x.Status == 1).ToListAsync();
            if (listdatadetile.Count == listdata.Count)
            {
                string sqlMain = @"update PB_TransportBill set State=5 where Id='" + billId + "'";
                await ExecuteSqlAsync(sqlMain);
            }
            else
            {
                throw new BusException("请卸完车后提交");
            }
        }



        /// <summary>
        /// 车俩验收卸车提交
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [Transactional]
        public async Task CheckBillDataAsync(CheckBillDTO data)
        {
            string billId = data.billqrcode.Split(',')?[1].ToString();
            //获取所有的卸车明细
            List<PB_TransportBillDetail> BillDetail = await Db.GetIQueryable<PB_TransportBillDetail>().Where(x => x.ParentId == billId).ToListAsync();
            var BillDetailNums = BillDetail.GroupBy(x => new { x.ParentId }).Select(x => new { ParentId = x.Key.ParentId, Nums = x.Sum(i => i.PackNums) }).FirstOrDefault();
            //获取已提交的卸车明细
            List<PB_TransportBillDetailList> DetailList = await Db.GetIQueryable<PB_TransportBillDetailList>().Where(x => x.BillId == billId && x.Status == 1).ToListAsync();
            var DetailListNums = DetailList.GroupBy(x => new { x.BillId }).Select(x => new { BillId = x.Key.BillId, Nums = x.Sum(i => i.ReceivingNums) }).FirstOrDefault();

            List<PB_TransportBillDetailList> Prodata = await Db.GetIQueryable<PB_TransportBillDetailList>().Where(x => x.BillId == billId && x.ProjectId == data.ProjectId).ToListAsync();
            var ProdataNums = Prodata.GroupBy(x => new { x.BillId }).Select(x => new { BillId = x.Key.BillId, Nums = x.Sum(i => i.ReceivingNums) }).FirstOrDefault();

            //获取项目下的所有的设计清单
            List<PB_DesignList> DesignList = await Db.GetIQueryable<PB_DesignList>().Where(x => x.ProjectId == data.ProjectId).ToListAsync();
            List<string> desIds = new List<string>();
            foreach (var item in DesignList)
            {
                desIds.Add(item.Id);
            }
            //获取所有设计清单的明细
            List<PB_DesignDetail> DesignDetail = await Db.GetIQueryable<PB_DesignDetail>().Where(x => desIds.Contains(x.ParentId) && x.ShipmentNums != x.RealNums).ToListAsync();
            string sqlMain = string.Empty;
            foreach (var item in Prodata)
            {
                var itemdata = DesignDetail.Where(x => x.MaterialId == item.MaterialId && x.State != 2).ToList();
                double? dnums = item.ReceivingNums;
                foreach (var ditem in itemdata)
                {
                    if (dnums > 0)
                    {
                        if (ditem.ShipmentNums.IsNullOrEmpty())
                        {
                            ditem.ShipmentNums = 0;
                        }
                        if (dnums <= (ditem.RealNums - ditem.ShipmentNums))
                        {
                            sqlMain += @" update PB_DesignDetail set ShipmentNums=IFNULL(ShipmentNums,0)+" + dnums + " where Id='" + ditem.Id + "'; ";
                            dnums -= dnums;
                        }
                        else
                        {
                            sqlMain += @" update PB_DesignDetail set ShipmentNums=IFNULL(ShipmentNums,0)+" + (ditem.RealNums - ditem.ShipmentNums) + " where Id='" + ditem.Id + "'; ";
                            dnums -= (ditem.RealNums - ditem.ShipmentNums);
                        }
                    }
                    else
                    {
                        continue;
                    }
                }

                sqlMain += @" update PB_TransportBillDetailList set `Status`=1 where Id='" + item.Id + "'; ";
            }
            await ExecuteSqlAsync(sqlMain);

            double? totalnums = 0;
            if (DetailListNums == null)
            {
                totalnums = ProdataNums.Nums;
            }
            else
            {
                totalnums = DetailListNums.Nums + ProdataNums.Nums;
            }
            if (BillDetailNums.Nums == totalnums)
            {
                sqlMain = @"update PB_TransportBill set State=5,AcceptanceTime=NOW() where Id='" + billId + "'";
                await ExecuteSqlAsync(sqlMain);
            }
        }

        /// <summary>
        /// 车俩验收
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task CheckBillAsync(CheckBillDTO data)
        {
            string sqlMain = @"update PB_TransportBill set State=6,AcceptanceRemarks='" + data.AcceptanceRemarks + "' where Id='" + data.billqrcode + "'";
            await ExecuteSqlAsync(sqlMain);
        }

        /// <summary>
        /// 打印派车单接口
        /// </summary>
        /// <param name="ParentId"></param>
        /// <returns></returns>
        public async Task<List<PB_TransportBilllistinfo>> GetDataListInfo(string ParentId)
        {

            Expression<Func<PB_TransportBillGroup, PB_TransportBill, PB_DeliveryNotice, PB_Vehicle, Base_Department,
            PB_Project, PB_Customer, PB_TransportBilllistinfo>> select = (o, a, b, c, d, f, g) => new PB_TransportBilllistinfo
            {
                DeliveryNoticeIdName = b.Abstract,
                ProjectName = b.ProjectName,
                VehicleName = c.PlateNO,
                DeptIdName = d.Name,
                Project = f.Name,
                Address = b.Address,
                DeptAddress = d.Address,
                Factoryfax = d.Factoryfax,
                ContractNo = b.ContractNo,
                CooperativeUnitName = g.Name,//合作单位名称
                CooperativeUnitPhone = g.Phone,
                QrCode = a.QrCode,
                VehicleNameRen = c.DriverName,
                VehicleNamePhone = c.Iphone,
                Estimatedweight = a.EmptyNumber + a.RoughweightNumber,
                NetloadNumber = a.NetloadNumber,
                RoughweightNumber = a.RoughweightNumber,
                EmptyNumber = a.EmptyNumber,
                BillType = a.BillType,
                TrainNumber = a.TrainNumber == null ? "" : a.TrainNumber,

            };
            select = select.BuildExtendSelectExpre();
            var q = from o in Db.GetIQueryable<PB_TransportBillGroup>().AsExpandable()
                    join a in Db.GetIQueryable<PB_TransportBill>() on o.ParentId equals a.Id into oa
                    from a in oa.DefaultIfEmpty()
                    join b in Db.GetIQueryable<PB_DeliveryNotice>() on o.DeliveryNoticeId equals b.Id into ob
                    from b in ob.DefaultIfEmpty()
                    join c in Db.GetIQueryable<PB_Vehicle>() on a.Vehicle equals c.Id into ac
                    from c in ac.DefaultIfEmpty()
                    join d in Db.GetIQueryable<Base_Department>() on a.DeptId equals d.Id into ad
                    from d in ad.DefaultIfEmpty()
                    join f in Db.GetIQueryable<PB_Project>() on b.ProjectId equals f.Id into bf
                    from f in bf.DefaultIfEmpty()
                    join g in Db.GetIQueryable<PB_Customer>() on b.CooperativeUnitId equals g.Id into bg
                    from g in bg.DefaultIfEmpty()
                    select @select.Invoke(o, a, b, c, d, f, g);
            List<PB_TransportBilllistinfo> listdata = new List<PB_TransportBilllistinfo>();
            List<PB_TransportBillDetaillistinfo> SS = new List<PB_TransportBillDetaillistinfo>();
            var qdata = await q.Where(x => x.ParentId == ParentId).ToListAsync();
            foreach (var item in qdata)
            {



                PB_TransportBilllistinfo pblist = new PB_TransportBilllistinfo();
                #region
                pblist.Id = item.ParentId;
                pblist.CreateTime = item.CreateTime;
                pblist.CreatorId = item.CreatorId;
                pblist.Deleted = item.Deleted;
                pblist.DeliveryNoticeId = item.DeliveryNoticeId;
                pblist.DeliveryNoticeIdName = item.DeliveryNoticeIdName;
                pblist.Vehicle = item.Vehicle;
                pblist.VehicleName = item.VehicleName;
                pblist.SendTime = item.SendTime;
                pblist.IntoTime = item.IntoTime;
                pblist.DeliveryTime = item.DeliveryTime;
                pblist.Tunnage = item.Tunnage;
                pblist.QrCode = item.QrCode;
                pblist.DocumentMaker = item.DocumentMaker;
                pblist.EmptyNumber = item.EmptyNumber;
                pblist.EmptyTime = item.EmptyTime;
                pblist.NetloadNumber = item.NetloadNumber;
                pblist.RoughweightNumber = item.RoughweightNumber;
                pblist.RoughweightTime = item.RoughweightTime;
                pblist.WeighingPeople = item.WeighingPeople;
                pblist.DeliveryTime = item.DepartureTime;
                pblist.State = item.State;
                pblist.DriverName = item.DriverName;
                pblist.Iphone = item.Iphone;
                pblist.PlateNO = item.PlateNO;
                pblist.VehicleLicense = item.VehicleLicense;
                pblist.DrivingLicense = item.DrivingLicense;
                pblist.Estimatedweight = item.Estimatedweight;
                pblist.EnteringPlantMan = item.EnteringPlantMan;
                pblist.ExFactoryMan = item.ExFactoryMan;
                pblist.DeptId = item.DeptId;
                pblist.DeptIdName = item.DeptIdName;
                pblist.LoadingStartTime = item.LoadingStartTime;
                pblist.LoadingEndTime = item.LoadingEndTime;
                pblist.BillType = item.BillType;
                pblist.QrCode = item.QrCode;
                pblist.ProjectName = item.ProjectName;
                pblist.AcceptanceRemarks = item.AcceptanceRemarks;
                pblist.Project = item.Project;
                pblist.Address = item.Address;
                pblist.VehicleNameRen = item.VehicleNameRen;
                pblist.VehicleNamePhone = item.VehicleNamePhone;
                pblist.Factoryfax = item.Factoryfax;
                pblist.DeptAddress = item.DeptAddress;
                pblist.BillType = item.BillType;

                if (pblist.BillType == "Delivery")
                {
                    string SQL = "	SELECT BillDetail.MaterialIdName,BillDetail.Danwei,BillDetail.MaterialIdCode,BillDetail.PackNums,list.RealNums Nums,IFNULL(yifa.PackNums-BillDetail.PackNums,0) ShipmentNums FROM ( SELECT a.MaterialId,mater.`Name` MaterialIdName,mater.Code MaterialIdCode, items.`Name` AS Danwei,c.DesignId ,IFNULL(SUM(a.PackNums), 0) PackNums FROM pb_transportbilldetail a JOIN pb_material AS mater on a.MaterialId = mater.Id  join base_unititems AS items on mater.storageId = items.ID JOIN pb_pickupmain b ON a.PreparationNoteId = b.Id JOIN pb_deliverynoticeitem c on b.ParentId = c.Id WHERE  a.ParentId = '"+ParentId+ "' GROUP BY c.DesignId ,a.MaterialId ) AS BillDetail LEFT JOIN viewdesignlist AS list ON BillDetail.DesignId = list.ParentId AND BillDetail.MaterialId = list.Id LEFT JOIN viewYifa AS yifa on yifa.DesignId = BillDetail.DesignId AND yifa.MaterialId = BillDetail.MaterialId";
                    pblist.Subdata = await Db.GetListBySqlAsync<PB_TransportBillDetaillistinfo>(SQL); ;
                }
                else
                {
                    string SQL = "SELECT M.Id,M.`Name` AS MaterialIdName, M.`Code` AS MaterialIdCode, U.`Name` AS Danwei, IFNULL( sum(a.PackNums),0 ) PackNums FROM PB_TransportBillDetail AS a INNER JOIN PB_Material AS M ON a.MaterialId = M.Id  INNER JOIN Base_UnitItems AS U ON M.storageId = U.id WHERE  a.ParentId = '" + item.ParentId + "' GROUP BY M.Id";
                    pblist.Subdata = await Db.GetListBySqlAsync<PB_TransportBillDetaillistinfo>(SQL); ;
                }

                pblist.ContractNo = item.ContractNo;
                pblist.CooperativeUnitName = item.CooperativeUnitName;
                pblist.CooperativeUnitPhone = item.CooperativeUnitPhone;
                listdata.Add(pblist);
                #endregion
            }
            if (listdata.Count > 0)
            {
                return listdata;
            }
            else
            {
                throw new BusException("暂无数据");
            }


        }

        public async Task<PB_TransportBillDataDTO> GetBillDataAsyncids(string id)
        {

            //Expression<Func<PB_TransportBillDetail,PB_TransportBill, PB_PackList,PB_Material,PB_TransportBillMXDTO>> selects = (a, b, c,d) => new PB_TransportBillMXDTO
            //{
            //   Nums=c.Nums,
            //   Wight=d.Width,
            //   TheoreticalWeight=c.Nums*(d.Width==null?0: d.Width),
            //};
            //selects = selects.BuildExtendSelectExpre();
            //var qts= from a in Db.GetIQueryable<PB_TransportBillDetail>().AsExpandable()
            //         join b in Db.GetIQueryable<PB_TransportBill>() on a.ParentId equals b.Id into ab
            //         from b in ab.DefaultIfEmpty()
            //         join c in Db.GetIQueryable<PB_PackList>() on a.PackId equals c.Id into ac
            //         from c in ac.DefaultIfEmpty()
            //         join d in Db.GetIQueryable<PB_Material>() on c.MaterialId equals d.Id into cd
            //         from d in cd.DefaultIfEmpty()
            //         select @selects.Invoke(a, b, c,d);
            //        var qs = await qts.Where(x => x.r == id).FirstOrDefaultAsync();
            //if (qs!=null) {
            //    PB_TransportBillDataDTO pbdatas = new PB_TransportBillDataDTO();
            //    pbdatas.PB_TransportBill.TheoreticalWeight = qs.TheoreticalWeight;
            //}
            Expression<Func<PB_TransportBillGroup, PB_TransportBill, PB_DeliveryNotice, PB_Vehicle, Base_Department,
           PB_Project, PB_Customer, PB_TransportBilllistinfo>> @selectSS = (o, a, b, c, d, f, g) => new PB_TransportBilllistinfo
           {
               DeliveryNoticeIdName = b.ProjectName,
               VehicleName = c.PlateNO,
               DeptIdName = d.Name,
               Project = f.Name,
               ProjectId = b.Id,
               Address = b.Address,
               DeptAddress = d.Address,
               Factoryfax = d.Factoryfax,
               ContractNo = b.ContractNo,
               CooperativeUnitName = g.Name,//合作单位名称
               CooperativeUnitPhone = g.Phone
           };
            @selectSS = @selectSS.BuildExtendSelectExpre();
            var LK = from o in Db.GetIQueryable<PB_TransportBillGroup>().AsExpandable()
                     join a in Db.GetIQueryable<PB_TransportBill>() on o.ParentId equals a.Id into oa
                     from a in oa.DefaultIfEmpty()
                     join b in Db.GetIQueryable<PB_DeliveryNotice>() on o.DeliveryNoticeId equals b.Id into ob
                     from b in ob.DefaultIfEmpty()
                     join c in Db.GetIQueryable<PB_Vehicle>() on a.Vehicle equals c.Id into ac
                     from c in ac.DefaultIfEmpty()
                     join d in Db.GetIQueryable<Base_Department>() on a.DeptId equals d.Id into ad
                     from d in ad.DefaultIfEmpty()
                     join f in Db.GetIQueryable<PB_Project>() on b.ProjectId equals f.Id into bf
                     from f in bf.DefaultIfEmpty()
                     join g in Db.GetIQueryable<PB_Customer>() on b.CooperativeUnitId equals g.Id into bg
                     from g in bg.DefaultIfEmpty()
                     select @selectSS.Invoke(o, a, b, c, d, f, g);
            var aa = LK.Where(m => m.ParentId == id).ToList();

            //var q = await Db.GetIQueryable<PB_TransportBill>().Where(x => x.Id == id).FirstOrDefaultAsync();
            Expression<Func<PB_TransportBill, PB_DeliveryNotice, PB_Vehicle, PB_TransportBillDetail, PB_PackList, PB_Material, PB_TransportBillMXDTO>> select = (a, b, c, d, e, f) => new PB_TransportBillMXDTO
            {
                PlateNO = c.PlateNO,
                SupplierId = c.SupplierId,
                ProjectName = b.ProjectName,
                TheoreticalWeight = e.Nums * (f.Width == null ? 0 : f.Width),

            };
            select = select.BuildExtendSelectExpre();
            var qt = from a in Db.GetIQueryable<PB_TransportBill>().AsExpandable()
                     join b in Db.GetIQueryable<PB_DeliveryNotice>() on a.DeliveryNoticeId equals b.Id into ab
                     from b in ab.DefaultIfEmpty()
                     join c in Db.GetIQueryable<PB_Vehicle>() on a.Vehicle equals c.Id into ac
                     from c in ac.DefaultIfEmpty()
                     join d in Db.GetIQueryable<PB_TransportBillDetail>() on a.Id equals d.ParentId into ad
                     from d in ad.DefaultIfEmpty()
                     join e in Db.GetIQueryable<PB_PackList>() on d.PackId equals e.Id into ae
                     from e in ae.DefaultIfEmpty()
                     join f in Db.GetIQueryable<PB_Material>() on e.MaterialId equals f.Id into af
                     from f in af.DefaultIfEmpty()
                     select @select.Invoke(a, b, c, d, e, f);
            var q = await qt.Where(x => x.Id == id).FirstOrDefaultAsync();
            if (q != null)
            {
                PB_TransportBillDataDTO pbdata = new PB_TransportBillDataDTO();

                pbdata.PB_TransportBill = q;
                var Weight = await getTheoreticalWeightAsync(q.Id);
                pbdata.PB_TransportBill.TheoreticalWeight = Convert.ToDouble(Weight[0].TheoreticalWeights);
                var qdata = await Db.GetDataTableWithSqlAsync("select t.*,IFNULL(tt.Nums,0) as unloadNums from ( select a.MaterialId,b.`Code`,b.`Name`,SUM(IFNULL(a.PackNums,0)) as Nums from PB_TransportBillDetail as a join PB_Material as b on a.MaterialId=b.Id where a.ParentId='" + q.Id + "' group by a.MaterialId,b.`Code`,b.`Name`) as t left join (select b.MaterialId,SUM(IFNULL(a.PackNums,0)) as Nums from PB_TransportBillDetail as a left join PB_PackList as b on a.PackId=b.Id where a.ParentId='" + q.Id + "' and a.Status=1 group by b.MaterialId) as tt on t.MaterialId=tt.MaterialId");
                List<TransportBillDetail> listdata = new List<TransportBillDetail>();
                foreach (DataRow dr in qdata.Rows)
                {
                    TransportBillDetail tbdata = new TransportBillDetail();
                    tbdata.MaterialCode = dr["Code"].ToString();
                    tbdata.MaterialName = dr["Name"].ToString();
                    tbdata.Nums = Convert.ToDouble(dr["Nums"]);
                    tbdata.unloadNums = Convert.ToDouble(dr["unloadNums"]);
                    listdata.Add(tbdata);
                }
                List<PB_Project> PB_Projects = new List<PB_Project>();
                foreach (var item in aa)
                {
                    PB_Project pB_Project = new PB_Project();
                    pB_Project.Name = item.Project;
                    pB_Project.Id = item.ProjectId;
                    PB_Projects.Add(pB_Project);
                }
                pbdata.TransportBillDetail = listdata;
                pbdata.ProjectList = PB_Projects;
                pbdata.TransportBillImg = await Db.GetIQueryable<PB_TransportBillImg>().Where(x => x.BillId == q.Id).ToListAsync();
                return pbdata;
            }
            else
            {
                throw new BusException("车辆暂无数据");
            }
        }
        /// <summary>
        /// 皮重过磅
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task Empty(PB_TransportBill data)
        {
            var datalist = await this.GetEntityAsync(data.Id);
            //如果是外协,则修改外协单的实际重量
            if (datalist.BillType == "Outsourcing_I")
            {
                if (data.RoughweightNumber.IsNullOrEmpty())
                {
                    throw new BusException("毛重不能为空！");
                }
                if (data.EmptyNumber.IsNullOrEmpty())
                {
                    throw new BusException("皮重不能为空！");
                }
                //string sqlMain = $"update PB_OutsourcingBill SET BackWeight =IFNULL(BackWeight,0) + {data.RoughweightNumber - data.EmptyNumber}  WHERE Id = '{data.DeliveryNoticeId}';";
                //await ExecuteSqlAsync(sqlMain);
            }


            // 修改主数据状态
            {
                datalist.EmptyNumber = data.EmptyNumber;
                datalist.EmptyTime = DateTime.Now;
                datalist.WeighingPeople = data.WeighingPeople;

                datalist.NetloadNumber = data.RoughweightNumber - datalist.EmptyNumber;
                await UpdateAsync(datalist);
            }
        }
        /// <summary>
        /// 毛重过磅
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task Roughweight(PB_TransportBill data)
        {
            var datalist = await this.GetEntityAsync(data.Id);
            ///车辆毛重过磅后台添加毛重不能小于皮重  2022/3/4
            if (data.RoughweightNumber < data.EmptyNumber)
            {
                throw new BusException("毛重不能小于皮重！");
            }
            //如果是外协,则修改外协单的实际重量
            if (datalist.BillType == "Outsourcing_O")
            {
                if (data.RoughweightNumber.IsNullOrEmpty())
                {
                    throw new BusException("毛重不能为空！");
                }
                if (data.EmptyNumber.IsNullOrEmpty())
                {
                    throw new BusException("皮重不能为空！");
                }
                //string sqlMain = $"update PB_OutsourcingBill SET Weight =IFNULL(Weight,0) + {data.RoughweightNumber - data.EmptyNumber}, Status =4   WHERE Id = '{data.DeliveryNoticeId}';";
                //await ExecuteSqlAsync(sqlMain);
            }
            // 修改主数据状态
            {
                datalist.RoughweightNumber = data.RoughweightNumber;
                datalist.RoughweightTime = DateTime.Now;
                datalist.WeighingPeople = data.WeighingPeople;
                datalist.NetloadNumber = data.RoughweightNumber - data.EmptyNumber;
                await UpdateAsync(datalist);
            }
        }

        /// <summary>
        /// 车辆毛重超载卸车获取车辆信息
        /// </summary>
        /// <param name="deptId">登录人组织Id</param>
        /// <param name="BillType">车辆类型</param>
        /// <returns></returns>
        public async Task<List<PB_TransportBillVehicleDTO>> GetUnloadCarInformationAsync(string deptId, string BillType)
        {
            Expression<Func<PB_TransportBill, PB_Vehicle, PB_TransportBillVehicleDTO>> select = (a, b) => new PB_TransportBillVehicleDTO
            {
                PlateName = b.PlateNO
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in Db.GetIQueryable<PB_TransportBill>().AsExpandable()
                    join b in Db.GetIQueryable<PB_Vehicle>() on a.Vehicle equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    select @select.Invoke(a, b);

            if (!deptId.IsNullOrEmpty())
            {
                //获取登录人法人一级组织信息
                var dpdata = await _opdept.GetOperatorDept();
                List<string> liststr = new List<string>();
                liststr.Add(dpdata.DetpId);
                //获取所有的部门信息
                List<Base_Department> deptlist = await Db.GetIQueryable<Base_Department>().ToListAsync();
                var listdata = deptlist.Where(x => x.ParentId == dpdata.DetpId).ToList();
                foreach (var item in listdata)
                {
                    liststr.Add(item.Id);
                    GetDeptItem(item.Id, liststr, deptlist);
                }
                if (BillType.IsNullOrEmpty())
                {
                    BillType = "Delivery";
                    q = q.Where(x => liststr.Contains(x.DeptId) && x.State >= 2 && x.State < 4 && x.BillType == BillType);
                }
                else
                {
                    q = q.Where(x => liststr.Contains(x.DeptId) && (x.State == 0) && x.BillType == BillType);
                }

            }
            var res = await q.ToListAsync();
            if (res.Count > 0)
            {
                return res;
            }
            else
            {
                throw new BusException("暂无数据");
            }
        }

        /// <summary>
        /// 车辆毛重超载卸车
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [Transactional]
        public async Task<BillUnloadDTO> UnloadTransportBillDetailAsync(PB_TransportBillDetailDTO data)
        {
            string sqlMain = string.Empty;
            string qrcodemodel = data.PackQrCode.Split(',')?[0].ToString();
            string packid = string.Empty;
            string materialId = string.Empty;
            string jobid = "";
            if (qrcodemodel == "13")
            {
                packid = data.PackQrCode.Split(',')[1].ToString();
            }
            else if (qrcodemodel == "04")
            {
                var model = data.PackQrCode.Split(',');
                if (model.Length > 2)
                {
                    if (model.Length < 4)
                    {
                        throw new BusException("请扫描正确的二维码信息");
                    }
                    else
                    {
                        materialId = model?[3].ToString();
                    }
                }
                else
                {
                    materialId = model?[1].ToString();
                }
            }
            else if (qrcodemodel == "14")
            {
                jobid = data.PackQrCode.Split(',')[1].ToString();
            }
            BillUnloadDTO billdata = new BillUnloadDTO();
            if (qrcodemodel == "13")
            {
                //查询包信息
                PB_PackList packdata = await Db.GetIQueryable<PB_PackList>().Where(x => x.Id == packid).FirstOrDefaultAsync();
                if (packdata == null)
                {
                    throw new BusException("请输入或扫描正确的包信息!");
                }
                //标准包
                if (packdata.PackageType == 0)
                {
                    //查询车上标准包的信息
                    PB_TransportBillDetail billdetail = await Db.GetIQueryable<PB_TransportBillDetail>().Where(x => x.ParentId == data.BillId && x.PackId == packid).FirstOrDefaultAsync();
                    if (billdetail != null)
                    {
                        PB_Material materdata = await Db.GetIQueryable<PB_Material>().Where(x => x.Id == billdetail.MaterialId).FirstOrDefaultAsync();

                        billdata.Id = billdetail.Id;
                        billdata.PackId = billdetail.PackId;
                        billdata.MaterialId = billdetail.MaterialId;
                        billdata.Nums = billdetail.PackNums;
                        billdata.PackName = packdata.BoxName;
                        billdata.MaterialSpec = materdata.Spec;
                        billdata.CreateTime = DateTime.Now;
                        billdata.DesignDetailId = billdetail.DesignDetailId;
                        billdata.PreparationNoteId = billdetail.PreparationNoteId;
                        billdata.JobId = "";
                        //把当前包卸车
                        sqlMain = @" delete from PB_TransportBillDetail where ParentId='" + data.BillId + "' and PackId='" + packid + "'; ";
                        await ExecuteSqlAsync(sqlMain);
                    }
                    else
                    {
                        throw new BusException("请检查包是否在这辆车上!");
                    }
                }
                else if (packdata.PackageType == 1)   //混合包
                {
                    //查询车上混合包的信息
                    List<PB_TransportBillDetail> billdetail = await Db.GetIQueryable<PB_TransportBillDetail>().Where(x => x.ParentId == data.BillId && x.PackId == packid).ToListAsync();
                    if (billdetail.Count > 0)
                    {
                        //
                        var detaildata = billdetail.GroupBy(x => new { x.PackId }).Select(x => new
                        {
                            PackId = x.Key.PackId,
                            Nums = x.Sum(i => i.PackNums)
                        }).FirstOrDefault();
                        billdata.Id = "";
                        billdata.PackId = detaildata.PackId;
                        billdata.MaterialId = "";
                        billdata.Nums = detaildata.Nums;
                        billdata.PackName = packdata.BoxName;
                        billdata.MaterialSpec = "";
                        billdata.CreateTime = DateTime.Now;
                        billdata.DesignDetailId = "";
                        billdata.PreparationNoteId = "";
                        billdata.JobId = "";

                        sqlMain = @" delete from PB_TransportBillDetail where ParentId='" + data.BillId + "' and PackId='" + packid + "'; ";
                        await ExecuteSqlAsync(sqlMain);
                    }
                    else
                    {
                        throw new BusException("请检查包是否在这辆车上!");
                    }
                }
            }
            else if (qrcodemodel == "04")   //单个物料
            {
                List<PB_TransportBillDetail> billdetail = await Db.GetIQueryable<PB_TransportBillDetail>().Where(x => x.ParentId == data.BillId && x.PackId == "" && x.MaterialId == materialId).ToListAsync();
                if (billdetail.Count > 0)
                {
                    PB_Material materdata = await Db.GetIQueryable<PB_Material>().Where(x => x.Id == materialId).FirstOrDefaultAsync();
                    double? dnums = data.Nums;
                    foreach (var item in billdetail)
                    {
                        if (dnums > 0)
                        {
                            if (item.PackNums == dnums)
                            {
                                sqlMain += @" delete from PB_TransportBillDetail where Id='" + item.Id + "'; ";
                            }
                            else if (item.PackNums < dnums)
                            {
                                if (dnums >= item.PackNums)
                                {
                                    dnums -= item.PackNums;
                                    sqlMain += @" delete from PB_TransportBillDetail where Id='" + item.Id + "'; ";
                                }
                                else
                                {
                                    dnums -= dnums;
                                    sqlMain += @" update PB_TransportBillDetail set PackNums=IFNULL(PackNums,0)-" + dnums + " where Id='" + item.Id + "'; ";
                                }
                            }
                            else if (item.PackNums > dnums)
                            {
                                sqlMain += @" update PB_TransportBillDetail set PackNums=IFNULL(PackNums,0)-" + dnums + " where Id='" + item.Id + "'; ";
                                dnums -= dnums;
                            }
                        }
                    }
                    await ExecuteSqlAsync(sqlMain);
                    var detaildata = billdetail.GroupBy(x => new { x.DesignDetailId, x.PreparationNoteId, x.MaterialId }).Select(x => new
                    {
                        DesignDetailId = x.Key.DesignDetailId,
                        PreparationNoteId = x.Key.PreparationNoteId,
                        MaterialId = x.Key.MaterialId
                    }).FirstOrDefault();
                    billdata.Id = IdHelper.GetId();
                    billdata.PackId = "";
                    billdata.MaterialId = materialId;
                    billdata.Nums = data.Nums;
                    billdata.PackName = materdata.Name;
                    billdata.MaterialSpec = materdata.Spec;
                    billdata.CreateTime = DateTime.Now;
                    billdata.DesignDetailId = detaildata.DesignDetailId;
                    billdata.PreparationNoteId = detaildata.PreparationNoteId;
                    billdata.JobId = "";
                }
                else
                {
                    throw new BusException("请检查物料是否在这辆车上!");
                }
            }
            else if (qrcodemodel == "14")
            {
                PB_TransportBillDetail billdetail = await Db.GetIQueryable<PB_TransportBillDetail>().Where(x => x.ParentId == data.BillId && x.JobId == jobid).FirstOrDefaultAsync();
                PB_Material materdata = await Db.GetIQueryable<PB_Material>().Where(x => x.Id == billdetail.MaterialId).FirstOrDefaultAsync();
                sqlMain = @"  delete from PB_TransportBillDetail where JobId='" + jobid + "'";
                await ExecuteSqlAsync(sqlMain);
                billdata.Id = IdHelper.GetId();
                billdata.PackId = "";
                billdata.MaterialId = billdetail.MaterialId;
                billdata.Nums = 1;
                billdata.PackName = materdata.Name;
                billdata.MaterialSpec = materdata.Spec;
                billdata.CreateTime = DateTime.Now;
                billdata.DesignDetailId = billdetail.DesignDetailId;
                billdata.PreparationNoteId = billdetail.PreparationNoteId;
                billdata.JobId = jobid;
            }
            return billdata;
        }

        /// <summary>
        /// 车辆毛重超载卸车扫描单个物料
        /// </summary>
        /// <param name="billId">派车单Id</param>
        /// <param name="qrcode">单个物料二维码</param>
        /// <returns></returns>
        public async Task<TransportBillDetailMaterialDTO> GetBillDetailMaterialDataAsync(string billId, string qrcode)
        {
            string materialId = string.Empty;
            var model = qrcode.Split(',');
            if (model.Length > 2)
            {
                if (model.Length < 4)
                {
                    throw new BusException("请扫描正确的二维码信息");
                }
                else
                {
                    materialId = model?[3].ToString();
                }
            }
            else
            {
                materialId = model?[1].ToString();
            }

            Expression<Func<PB_TransportBillDetail, PB_Material, TransportBillDetailMaterialDTO>> select = (a, b) => new TransportBillDetailMaterialDTO
            {
                ParentId = a.ParentId,
                MaterialId = a.MaterialId,
                Code = b.Code,
                Name = b.Name,
                Spec = b.Spec,
                PackId = a.PackId,
                Nums = a.PackNums
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in Db.GetIQueryable<PB_TransportBillDetail>().AsExpandable()
                    join b in Db.GetIQueryable<PB_Material>() on a.MaterialId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    select @select.Invoke(a, b);
            var detaildata = await q.Where(x => x.ParentId == billId && x.MaterialId == materialId && x.PackId == "").ToListAsync();
            var data = detaildata.GroupBy(x => new { x.ParentId, x.MaterialId, x.Code, x.Name, x.Spec }).Select(x => new
            {
                ParentId = x.Key.ParentId,
                MaterialId = x.Key.MaterialId,
                Code = x.Key.Code,
                Name = x.Key.Name,
                Spec = x.Key.Spec,
                Nums = x.Sum(i => i.Nums)
            }).FirstOrDefault();
            if (data.IsNullOrEmpty())
            {
                throw new Exception("请检查是否扫描装车了");
            }
            TransportBillDetailMaterialDTO BillDetail = new TransportBillDetailMaterialDTO();
            BillDetail.ParentId = data.ParentId;
            BillDetail.MaterialId = data.MaterialId;
            BillDetail.Code = data.Code;
            BillDetail.Name = data.Name;
            BillDetail.Spec = data.Spec;
            BillDetail.Nums = data.Nums;
            return BillDetail;
        }

        /// <summary>
        /// 车辆毛重超载卸车移除
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [Transactional]
        public async Task DeleteUnloadBillDetailAsync(BillUnloadDTO data)
        {
            Base_User userdata = await Db.GetIQueryable<Base_User>().Where(x => x.Id == _operator.UserId).FirstOrDefaultAsync();
            List<PB_TransportBillDetail> listdata = new List<PB_TransportBillDetail>();
            if (data.PackId.IsNullOrEmpty())
            {
                PB_TransportBillDetail detail = new PB_TransportBillDetail();
                detail.Id = IdHelper.GetId();
                detail.ParentId = data.BillId;
                detail.DesignDetailId = data.DesignDetailId;
                detail.PreparationNoteId = data.PreparationNoteId;
                detail.PackId = data.PackId;
                detail.MaterialId = data.MaterialId;
                detail.PretendCarUserId = _operator.UserId;
                detail.PretendCarUserName = userdata.RealName;
                detail.PretendCarTime = DateTime.Now;
                detail.PackNums = data.Nums;
                detail.ReceiptQuantity = 0;
                detail.CreatorId = _operator.UserId;
                detail.CreatorName = userdata.RealName;
                detail.CreateTime = DateTime.Now;
                detail.Deleted = false;
                detail.Status = 0;
                detail.JobId = data.JobId;
                listdata.Add(detail);
            }
            else
            {
                List<PB_PackListInfo> infolist = await Db.GetIQueryable<PB_PackListInfo>().Where(x => x.PackId == data.PackId).ToListAsync();
                List<string> liststr = new List<string>();
                foreach (var item in infolist)
                {
                    liststr.Add(item.JobBookingId);
                }
                List<PB_JobBookingQrCode> joblist = await Db.GetIQueryable<PB_JobBookingQrCode>().Where(x => liststr.Contains(x.Id)).ToListAsync();
                var materdata = joblist.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId, Nums = x.Count() }).ToList();
                foreach (var item in materdata)
                {
                    PB_TransportBillDetail detail = new PB_TransportBillDetail();
                    detail.Id = IdHelper.GetId();
                    detail.ParentId = data.BillId;
                    detail.DesignDetailId = data.DesignDetailId;
                    detail.PreparationNoteId = data.PreparationNoteId;
                    detail.PackId = data.PackId;
                    detail.MaterialId = item.MaterialId;
                    detail.PretendCarUserId = _operator.UserId;
                    detail.PretendCarUserName = userdata.RealName;
                    detail.PretendCarTime = DateTime.Now;
                    detail.PackNums = item.Nums;
                    detail.ReceiptQuantity = 0;
                    detail.CreatorId = _operator.UserId;
                    detail.CreatorName = userdata.RealName;
                    detail.Deleted = false;
                    detail.Status = 0;
                    detail.JobId = "";
                    listdata.Add(detail);
                }
            }
            await Db.InsertAsync<PB_TransportBillDetail>(listdata);
        }

        /// <summary>
        /// 获取车辆信息外包
        /// </summary>
        /// <param name="deptId">登录人组织Id</param>
        /// <param name="BillType">车辆类型</param>
        /// 外协获取车辆信息
        public async Task<List<PB_TransportBillVehicleDTO>> GetoutCarInformationAsync(string deptId, string BillType)
        {
            Expression<Func<PB_TransportBill, PB_Vehicle, PB_TransportBillVehicleDTO>> select = (a, b) => new PB_TransportBillVehicleDTO
            {
                PlateName = b.PlateNO
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in Db.GetIQueryable<PB_TransportBill>().AsExpandable()
                    join b in Db.GetIQueryable<PB_Vehicle>() on a.Vehicle equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    select @select.Invoke(a, b);

            if (!deptId.IsNullOrEmpty())
            {
                //获取登录人法人一级组织信息
                var dpdata = await _opdept.GetOperatorDept();
                List<string> liststr = new List<string>();
                liststr.Add(dpdata.DetpId);
                //获取所有的部门信息
                List<Base_Department> deptlist = await Db.GetIQueryable<Base_Department>().ToListAsync();
                var listdata = deptlist.Where(x => x.ParentId == dpdata.DetpId).ToList();
                foreach (var item in listdata)
                {
                    liststr.Add(item.Id);
                    GetDeptItem(item.Id, liststr, deptlist);
                }

                if (BillType == "Outsourcing_O")
                {
                    q = q.Where(x => liststr.Contains(x.DeptId) && (x.State == 1) && x.BillType == BillType);
                }
                else if (BillType == "Outsourcing_I")
                {
                    q = q.Where(x => liststr.Contains(x.DeptId) && (x.State == 1) && x.BillType == BillType);
                }
                else
                {
                    q = q.Where(x => liststr.Contains(x.DeptId) && (x.State == 0) && x.BillType == BillType);
                }
            }
            var res = await q.ToListAsync();
            if (res.Count > 0)
            {
                return res;
            }


            else
            {
                throw new BusException("暂无数据");
            }

        }

        /// <summary>
        /// 根据车牌获取车辆信息
        /// </summary>
        /// <param name="plateno">车牌</param>
        /// <param name="deptId">登录人组织Id</param>
        /// <param name="BillType">车辆类型</param>
        /// <returns></returns>
        public async Task<PB_TransportBillDataDetailDTO> GetOutTransportBillDataAsync(string plateno, string deptId, string BillType)
        {
            //获取登录人法人一级组织信息
            var dpdata = await _opdept.GetOperatorDept();
            List<string> liststr = new List<string>();
            liststr.Add(dpdata.DetpId);
            //获取所有的部门信息
            List<Base_Department> deptlist = await Db.GetIQueryable<Base_Department>().ToListAsync();
            var listdata = deptlist.Where(x => x.ParentId == dpdata.DetpId).ToList();
            foreach (var item in listdata)
            {
                liststr.Add(item.Id);
                GetDeptItem(item.Id, liststr, deptlist);
            }
            //var q = await Db.GetIQueryable<PB_TransportBill>().Where(x => liststr.Contains(x.DeptId) && x.State == 1 && x.BillType == 0 && x.PlateNO == plateno).FirstOrDefaultAsync();
            Expression<Func<PB_TransportBill, PB_Vehicle, PB_TransportBillDataDetailDTO>> selectdata = (a, b) => new PB_TransportBillDataDetailDTO
            {
                PlateName = b.PlateNO
            };
            selectdata = selectdata.BuildExtendSelectExpre();
            var q = from a in Db.GetIQueryable<PB_TransportBill>().AsExpandable()
                    join b in Db.GetIQueryable<PB_Vehicle>() on a.Vehicle equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    select @selectdata.Invoke(a, b);
            //if (BillType.IsNullOrEmpty())
            //{
            //    BillType = "Outsourcing_O";
            //    q = q.Where(x => liststr.Contains(x.DeptId) && (x.State == 1) && x.BillType == BillType && x.PlateName == plateno);
            //}
            //else
            //{
            //    q = q.Where(x => liststr.Contains(x.DeptId) && (x.State == 0) && x.BillType == BillType && x.PlateName == plateno);
            //}

            if (BillType == "Outsourcing_O")
            {
                q = q.Where(x => liststr.Contains(x.DeptId) && (x.State == 1) && x.BillType == BillType && x.PlateName == plateno);
            }
            else if (BillType == "Outsourcing_I")
            {
                q = q.Where(x => liststr.Contains(x.DeptId) && (x.State == 1) && x.BillType == BillType && x.PlateName == plateno);
            }
            else
            {
                q = q.Where(x => liststr.Contains(x.DeptId) && (x.State == 0) && x.BillType == BillType && x.PlateName == plateno);
            }
            var qd = await q.FirstOrDefaultAsync();
            if (qd != null)
            {
                PB_TransportBillDataDetailDTO pbdata = new PB_TransportBillDataDetailDTO();
                pbdata.Id = qd.Id;
                pbdata.CreateTime = qd.CreateTime;
                pbdata.CreatorId = qd.CreatorId;
                pbdata.Deleted = qd.Deleted;
                //pbdata.DesignListid = q.DesignListid;
                //pbdata.DispatchBillid = q.DispatchBillid;
                //pbdata.PickingBillid = q.PickingBillid;
                pbdata.DeliveryNoticeId = qd.DeliveryNoticeId;
                pbdata.Vehicle = qd.Vehicle;
                pbdata.SendTime = qd.SendTime;
                pbdata.IntoTime = qd.IntoTime;
                pbdata.DeliveryTime = qd.DeliveryTime;
                pbdata.Tunnage = qd.Tunnage;
                pbdata.DocumentMaker = qd.DocumentMaker;
                pbdata.EmptyNumber = qd.EmptyNumber;
                pbdata.EmptyTime = qd.EmptyTime;
                pbdata.NetloadNumber = qd.NetloadNumber;
                pbdata.RoughweightNumber = qd.RoughweightNumber;
                pbdata.RoughweightTime = qd.RoughweightTime;
                pbdata.WeighingPeople = qd.WeighingPeople;
                pbdata.DepartureTime = qd.DepartureTime;
                pbdata.State = qd.State;
                pbdata.DriverName = qd.DriverName;
                pbdata.Iphone = qd.Iphone;
                pbdata.PlateNO = qd.PlateNO;
                pbdata.PlateName = qd.PlateName;
                pbdata.VehicleLicense = qd.VehicleLicense;
                pbdata.DrivingLicense = qd.DrivingLicense;
                pbdata.Estimatedweight = qd.Estimatedweight;
                pbdata.EnteringPlantMan = qd.EnteringPlantMan;
                pbdata.ExFactoryMan = qd.ExFactoryMan;
                //Expression<Func<PB_TransportBillDetail, PB_PackList, PB_TransportBillDetailDataDTO>> select = (a, b) => new PB_TransportBillDetailDataDTO
                //{
                //    PackName = b.BoxName,
                //    BoxNo = b.BoxNo,
                //    Nums = b.Nums
                //};
                //select = select.BuildExtendSelectExpre();
                //var qdata = from a in Db.GetIQueryable<PB_TransportBillDetail>().AsExpandable()
                //        join b in Db.GetIQueryable<PB_PackList>() on a.PackId equals b.Id into ab
                //        from b in ab.DefaultIfEmpty()
                //        select @select.Invoke(a, b);
                //qdata = qdata.Where(x => x.ParentId == qd.Id).OrderByDescending(x => x.CreateTime);
                string sqlMain = @"select *,ROW_NUMBER() over(order by CreateTime desc) as rowsid from ( SELECT a.Id,a.PackId,a.MaterialId,a.PackNums as Nums,b.BoxName as PackName,c.Spec as MaterialSpec,a.CreateTime FROM PB_TransportBillDetail as a join PB_PackList as b on a.PackId=b.Id join PB_Material as c on a.MaterialId=c.Id where a.ParentId='" + qd.Id + "' and b.PackageType=0 UNION ALL select '' as Id,PackId,'' as MaterialId,SUM(Nums) as Nums,PackName,'' as MaterialSpec,CreateTime from ( SELECT a.PackId,b.BoxName as PackName,a.PackNums as Nums,DATE_FORMAT(a.CreateTime,'%Y-%m-%d') as CreateTime FROM PB_TransportBillDetail as a join PB_PackList as b on a.PackId=b.Id join PB_Material as c on a.MaterialId=c.Id where a.ParentId='" + qd.Id + "' and b.PackageType=1 ) as t group by PackId,PackName,CreateTime UNION ALL select a.Id,a.PackId,a.MaterialId,a.PackNums as Nums,b.`Name` as PackName,b.Spec as MaterialSpec,a.CreateTime from PB_TransportBillDetail as a join PB_Material as b on a.MaterialId=b.Id where a.ParentId='" + qd.Id + "' and a.PackId='' ) as t";
                var transportbilldetail = await Db.GetListBySqlAsync<PB_TransportBillDetailListData>(sqlMain);
                pbdata.TransportBillDetail = transportbilldetail;
                return pbdata;
            }
            else
            {
                throw new BusException("请核对车辆信息");
            }
        }


        /// <summary>
        /// 外协扫描包装车
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        /// 扫描装车,并且减库存
        [Transactional]
        public async Task AddOutTransportBillDetailAsync(PB_TransportBillDetailDTO data)
        {
            string qrcodemodel = data.PackQrCode.Split(',')?[0].ToString();
            string packid = string.Empty;
            string materialId = string.Empty;
            if (qrcodemodel == "13")
            {
                packid = data.PackQrCode.Split(',')[1].ToString();
            }
            else
            {
                throw new BusException("请扫描正确的二维码信息");
            }
            //根据包获取对应的外协任务单
            Expression<Func<PB_OutsourcingBill, PB_OutsourcingBillDetail, PB_CirculationBill, PB_PickOutsourcingBillDataDTO>> select = (a, b, c) => new PB_PickOutsourcingBillDataDTO
            {
                PackId = c.PackId,
                CirculationId = c.Id
            };

            select = select.BuildExtendSelectExpre();
            var q = from a in Db.GetIQueryable<PB_OutsourcingBill>().AsExpandable()
                    join b in Db.GetIQueryable<PB_OutsourcingBillDetail>() on a.Id equals b.ParentId into ab
                    from b in ab.DefaultIfEmpty()
                    join c in Db.GetIQueryable<PB_CirculationBill>() on a.Id equals c.TaskId into ac
                    from c in ac.DefaultIfEmpty()
                    select @select.Invoke(a, b, c);
            var mainList = q.Where(x => x.PackId == packid).ToList();
            var maindata = mainList.GroupBy(x => new { x.Id, x.Status }).Select(x => new { OutsourcingBillId = x.Key.Id, Status = x.Key.Status }).FirstOrDefault();
            if (maindata != null)
            {
                if (maindata.Status != 3)
                {
                    throw new BusException("该包还没准备完毕,还不能装车!");
                }
            }
            else
            {
                throw new BusException("请检查包是否出库");
            }

            //查询外协单对应的外协单
            Expression<Func<PB_TransportBill, PB_TransportBillGroup, PB_TransportBillGroupListDataDTO>> selectNoticeId = (a, b) => new PB_TransportBillGroupListDataDTO
            {
                DeliveryNoticeId = b.DeliveryNoticeId
            };
            selectNoticeId = selectNoticeId.BuildExtendSelectExpre();
            var qNoticeId = from a in Db.GetIQueryable<PB_TransportBill>().AsExpandable()
                            join b in Db.GetIQueryable<PB_TransportBillGroup>() on a.Id equals b.ParentId into ab
                            from b in ab.DefaultIfEmpty()
                            select @selectNoticeId.Invoke(a, b);
            var BillGrouplist = await qNoticeId.Where(x => x.Id == data.BillId && x.State == 1).ToListAsync();
            //匹配包与派车单对应的发货通知单是否存在
            var groupdata = BillGrouplist.Find(x => x.DeliveryNoticeId == maindata.OutsourcingBillId);
            if (groupdata == null)
            {
                throw new BusException("请核对车辆对应的发货通知单");
            }
            //获取操作人
            Base_User basedata = await Db.GetIQueryable<Base_User>().Where(x => x.Id == _operator.UserId).FirstOrDefaultAsync();
            if (qrcodemodel == "13")
            {
                // 获取这个包
                var PackListdata = await Db.GetIQueryable<PB_PackList>().Where(x => x.Id == data.PackQrCode.Split(',')[1].ToString()).FirstOrDefaultAsync();
                if (PackListdata.PackageType == 0)
                {
                    //根据包码获取到对应的生产流转单
                    var packdata = await Db.GetIQueryable<PB_CirculationBill>().Where(x => x.PackId == packid).FirstOrDefaultAsync();
                    if (packdata != null)
                    {
                        // 查询派车单和对应的包
                        var billdata = await Db.GetIQueryable<PB_TransportBillDetail>().Where(x => x.ParentId == data.BillId && x.PackId == packid).FirstOrDefaultAsync();
                        if (billdata == null)
                        {
                            //装车
                            PB_TransportBillDetail pbdata = new PB_TransportBillDetail();
                            pbdata.Id = IdHelper.GetId();
                            pbdata.ParentId = data.BillId;
                            //pbdata.DesignDetailId = packdata.subId;
                            //pbdata.PreparationNoteId = packdata.stockupId;
                            pbdata.PackId = packid;
                            pbdata.MaterialId = packdata.MaterialId;
                            pbdata.PretendCarUserId = _operator.UserId;
                            pbdata.PretendCarUserName = basedata.RealName;
                            pbdata.PretendCarTime = DateTime.Now;
                            pbdata.PackNums = packdata.StatisticalQuantity;
                            pbdata.ReceiptQuantity = 0;
                            pbdata.CreatorId = _operator.UserId;
                            pbdata.CreatorName = basedata.RealName;
                            pbdata.CreateTime = DateTime.Now;
                            pbdata.Deleted = false;
                            pbdata.Status = 0;
                            await Db.InsertAsync(pbdata);

                            #region 减库存
                            //获取仓库要出库的包信息
                            Expression<Func<IT_LocalDetail, PB_PackList, StockPackListDTO>> packselect = (a, b) => new StockPackListDTO
                            {
                                BoxName = b.BoxName,
                                PackageType = b.PackageType
                            };
                            packselect = packselect.BuildExtendSelectExpre();
                            var packdata1 = from a in Db.GetIQueryable<IT_LocalDetail>().AsExpandable()
                                            join b in Db.GetIQueryable<PB_PackList>() on a.PackId equals b.Id into ab
                                            from b in ab.DefaultIfEmpty()
                                            select @packselect.Invoke(a, b);
                            var pack = await packdata1.Where(x => x.PackId == packid && x.LocalId == packdata.LocationId).FirstOrDefaultAsync();

                            if (pack == null)
                            {
                                throw new BusException("库存没有这个包,请重新扫描!");
                            }
                            else
                            {
                                await ExecuteSqlAsync("delete from PB_Stock where PackId='" + pack.PackId + "'");
                            }
                            //删除库存


                            //删除库存明细表
                            await ExecuteSqlAsync("delete from IT_LocalDetail where PackId='" + pack.PackId + "'");

                            //修改货架上存放货物存汇总表的审核前数量和新旧数量
                            string itsql = string.Empty;
                            if (pack.OldOrNew == 0)
                            {
                                itsql = @"update IT_LocalMaterial set Nums_O=IFNULL(Nums_O,0)-" + pack.Num + ",ScanNum=IFNULL(ScanNum,0)-" + pack.Num + " where StorId='" + pack.StorId + "' and LocalId='" + pack.LocalId + "' and MaterialId='" + pack.MaterialId + "'";
                            }
                            else if (pack.OldOrNew == 1)
                            {
                                itsql = @"update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)-" + pack.Num + ",ScanNum=IFNULL(ScanNum,0)-" + pack.Num + " where StorId='" + pack.StorId + "' and LocalId='" + pack.LocalId + "' and MaterialId='" + pack.MaterialId + "'";
                            }
                            await ExecuteSqlAsync(itsql);

                            //修改物料审核前数量
                            string msql = @"update PB_Material set ScanNum=IFNULL(ScanNum,0)-" + pack.Num + " where Id='" + pack.MaterialId + "'";
                            await ExecuteSqlAsync(msql);

                            //修改包的状态为已出库
                            await ExecuteSqlAsync("update PB_PackList set Status=4,OutStorTime=NOW() where Id='" + pack.PackId + "'");
                            #endregion


                            List<PB_TransportBillDetail> listdata = await Db.GetIQueryable<PB_TransportBillDetail>().Where(x => x.ParentId == data.BillId).ToListAsync();
                            if (listdata.Count == 1)
                            {
                                string sqlMain = @"update PB_TransportBill set LoadingStartTime='" + DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss") + "' where id='" + data.BillId + "'";
                                await ExecuteSqlAsync(sqlMain);
                            }
                        }
                    }

                }
                else
                {
                    throw new BusException("请扫描未装车的包信息");
                }
            }

        }
        /// <summary>
        /// 移除外协装车包
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [Transactional]
        public async Task DeleteeOutTransportBillDataDetailAsync(PB_TransportBillDetailListData data)
        {
            //获取操作人的用户信息
            Base_User basedata = await Db.GetIQueryable<Base_User>().Where(x => x.Id == _operator.UserId).FirstOrDefaultAsync();
            // 获取这个包
            PB_PackList pbdata = await Db.GetIQueryable<PB_PackList>().Where(x => x.Id == data.PackId).FirstOrDefaultAsync();
            Expression<Func<PB_TransportBillDetail, PB_CirculationBill, PB_Location, PB_Material, PB_OutTransportBillDetailDTO>> packselect = (a, b, c, d) => new PB_OutTransportBillDetailDTO
            {
                LocationId = c.Id,
                StorId = c.StorId,
                AreaId = c.AreaId,
                RackId = c.RackId,
                MeasureId = d.storageId
            };
            packselect = packselect.BuildExtendSelectExpre();
            var packdata = from a in Db.GetIQueryable<PB_TransportBillDetail>().AsExpandable()
                           join b in Db.GetIQueryable<PB_CirculationBill>() on a.PackId equals b.PackId into ab
                           from b in ab.DefaultIfEmpty()
                           join c in Db.GetIQueryable<PB_Location>() on b.LocationId equals c.Id into bc
                           from c in bc.DefaultIfEmpty()
                           join d in Db.GetIQueryable<PB_Material>() on a.MaterialId equals d.Id into ac
                           from d in ac.DefaultIfEmpty()
                           select @packselect.Invoke(a, b, c, d);
            var unloaddata = await packdata.Where(x => x.Id == data.Id).FirstOrDefaultAsync();


            string sqlMain = @" delete from PB_TransportBillDetail where Id='" + data.Id + "'; ";
            //修改包的状态为入库
            sqlMain += @" update PB_PackList set Status=3 where Id='" + data.PackId + "'; ";
            await ExecuteSqlAsync(sqlMain);

            PB_Stock stockdata = new PB_Stock();
            stockdata.Id = IdHelper.GetId();
            stockdata.PackId = unloaddata.PackId;
            stockdata.StorId = unloaddata.StorId;
            stockdata.LocationId = unloaddata.LocationId;
            stockdata.StockNumber = data.Nums;
            stockdata.MaterialId = data.MaterialId;
            stockdata.CreatorId = _operator.UserId;
            stockdata.CreatorName = basedata.RealName;
            stockdata.CreateTime = DateTime.Now;
            stockdata.OperatorId = _operator.UserId;
            stockdata.Type = 1;
            stockdata.OrderID = "";
            stockdata.OldOrNew = pbdata.OldOrNew;
            stockdata.AreaId = unloaddata.AreaId;
            stockdata.RackId = unloaddata.RackId;
            await Db.InsertAsync<PB_Stock>(stockdata);

            PB_StockLog stockdatalog = new PB_StockLog();
            stockdatalog.Id = IdHelper.GetId();
            stockdatalog.PackId = unloaddata.PackId;
            stockdatalog.StorId = unloaddata.StorId;
            stockdatalog.LocationId = unloaddata.LocationId;
            stockdatalog.StockNumber = data.Nums;
            stockdatalog.MaterialId = data.MaterialId;
            stockdatalog.CreatorId = _operator.UserId;
            stockdatalog.CreatorName = basedata.RealName;
            stockdatalog.CreateTime = DateTime.Now;
            stockdatalog.OperatorId = _operator.UserId;
            stockdatalog.Type = 1;
            stockdatalog.OrderID = "";
            stockdatalog.OldOrNew = pbdata.OldOrNew;
            stockdatalog.State = 0;
            await Db.InsertAsync<PB_StockLog>(stockdatalog);

            IT_LocalDetail itdata = new IT_LocalDetail();
            itdata.Id = IdHelper.GetId();
            itdata.StorId = unloaddata.StorId;
            itdata.LocalId = unloaddata.LocationId;
            itdata.MaterialId = data.MaterialId;
            itdata.MeasureId = unloaddata.MeasureId;
            itdata.BarCode = pbdata.QrCode;
            itdata.InTime = DateTime.Now;
            itdata.CreateTime = DateTime.Now;
            itdata.CreatorId = _operator.UserId;
            itdata.Deleted = false;
            itdata.Num = pbdata.Nums;
            itdata.PackId = data.PackId;
            itdata.OldOrNew = pbdata.OldOrNew;
            itdata.JobId = "";
            await Db.InsertAsync<IT_LocalDetail>(itdata);
            sqlMain = "";
            if (pbdata.OldOrNew == 0)
            {
                sqlMain = @" update IT_LocalMaterial set Nums_O=IFNULL(Nums_O,0)+" + data.Nums + ",ScanNum=IFNULL(ScanNum,0)+" + data.Nums + " where MaterialId='" + pbdata.MaterialId + "' and StorId='" + unloaddata.StorId + "' and LocalId='" + unloaddata.LocationId + "' ";
            }
            else if (pbdata.OldOrNew == 1)
            {
                sqlMain = @" update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)+" + data.Nums + ",ScanNum=IFNULL(ScanNum,0)+" + data.Nums + " where MaterialId='" + pbdata.MaterialId + "' and StorId='" + unloaddata.StorId + "' and LocalId='" + unloaddata.LocationId + "' ";
            }
            await ExecuteSqlAsync(sqlMain);

        }

        [Transactional]
        public async Task CompleteOutTransportBillAsync(string billId)
        {
            //获取用户信息
            Base_User userdata = await Db.GetIQueryable<Base_User>().Where(x => x.Id == _operator.UserId).FirstOrDefaultAsync();
            ////更改派车单状态
            //string sqlMain = @"update PB_TransportBill set LoadingEndTime=NOW(),State=2 where id='" + billId + "'";
            //await ExecuteSqlAsync(sqlMain);


            //获取车辆所装包的信息
            Expression<Func<PB_TransportBillDetail, PB_TransportBill, PB_CirculationBill, PB_OutsourcingBill, PB_Material, PB_TransportBillDetailDataListDTO>> select = (a, b, c, d, e) => new PB_TransportBillDetailDataListDTO
            {
                LocalId = c.LocationId,
                Price = e.Price,
                ProjectId = d.ProjectId,
                OutsourcingCompanyId = d.OutsourcingCompanyId,
                OutsourcingBillId = d.Id
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in Db.GetIQueryable<PB_TransportBillDetail>().AsExpandable()
                    join b in Db.GetIQueryable<PB_TransportBill>() on a.ParentId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    join c in Db.GetIQueryable<PB_CirculationBill>() on a.PackId equals c.PackId into ac
                    from c in ac.DefaultIfEmpty()
                    join d in Db.GetIQueryable<PB_OutsourcingBill>() on c.TaskId equals d.Id into cd
                    from d in cd.DefaultIfEmpty()
                    join e in Db.GetIQueryable<PB_Material>() on a.MaterialId equals e.Id into ae
                    from e in ae.DefaultIfEmpty()
                    select @select.Invoke(a, b, c, d, e);
            var dataList = await q.Where(x => x.ParentId == billId).ToListAsync();



            //获取关联单号
            var Grouplist = await Db.GetIQueryable<PB_TransportBillGroup>().Where(x => x.ParentId == billId).ToListAsync();

            if (Grouplist.Count > 1)
            {
                foreach (var item in Grouplist)
                {
                    var data1 = dataList.Where(x => x.OutsourcingBillId == item.DeliveryNoticeId);

                    //出库单明细表
                    List<TD_OutStorDetail> listdetaildata = new List<TD_OutStorDetail>();
                    //仓库
                    string StorId = string.Empty;
                    //获区
                    string AreaId = string.Empty;
                    //货架
                    string RackId = string.Empty;
                    //出库单ID
                    string outid = IdHelper.GetId();
                    //定义数量
                    double dbnum = 0;

                    int i = 0;

                    foreach (var item1 in data1)
                    {
                        if (i == 0)
                        {
                            //获取仓库,获区货架
                            var locadata = await Db.GetIQueryable<PB_Location>().Where(x => x.Id == item1.LocalId).FirstOrDefaultAsync();
                            StorId = locadata.StorId;
                            AreaId = locadata.AreaId;
                            RackId = locadata.RackId;
                        }

                        TD_OutStorDetail outdetaildata = new TD_OutStorDetail();
                        outdetaildata.Id = IdHelper.GetId();
                        outdetaildata.StorId = StorId;
                        outdetaildata.OutStorId = outid;
                        outdetaildata.LocalId = item1.LocalId;
                        outdetaildata.AreaId = AreaId;
                        outdetaildata.RackId = RackId;
                        outdetaildata.MaterialId = item1.MaterialId;
                        outdetaildata.OutNum = Convert.ToDouble(item1.PackNums);
                        outdetaildata.Price = Convert.ToDouble(item1.Price);
                        outdetaildata.TotalAmt = Convert.ToDouble(item1.PackNums) * Convert.ToDouble(item1.Price);
                        dbnum += Convert.ToDouble(item1.PackNums);
                        outdetaildata.CreatorId = _operator.UserId;
                        outdetaildata.CreateTime = DateTime.Now;
                        outdetaildata.Deleted = false;
                        listdetaildata.Add(outdetaildata);
                        i++;

                    }
                    await Db.InsertAsync<TD_OutStorDetail>(listdetaildata);
                    //添加出库汇总明细表
                    List<TD_OutStorRecord> listtrecorddata = new List<TD_OutStorRecord>();
                    var listd = listdetaildata.GroupBy(x => new { x.StorId, x.LocalId, x.OutStorId, x.MaterialId, x.Price }).Select(x => new { StorId = x.Key.StorId, LocalId = x.Key.LocalId, OutStorId = x.Key.OutStorId, MaterialId = x.Key.MaterialId, Price = x.Key.Price, Nums = x.Sum(n => n.OutNum) });
                    foreach (var item1 in listd)
                    {
                        TD_OutStorRecord recodata = new TD_OutStorRecord();
                        recodata.Id = IdHelper.GetId();
                        recodata.StorId = item1.StorId;
                        recodata.OutStorId = item1.OutStorId;
                        recodata.MaterialId = item1.MaterialId;
                        recodata.OutNum = item1.Nums;
                        recodata.Price = item1.Price;
                        recodata.TotalAmt = item1.Nums * item1.Price;
                        recodata.CreateTime = DateTime.Now;
                        recodata.CreatorId = _operator.UserId;
                        recodata.Deleted = false;
                        listtrecorddata.Add(recodata);
                    }
                    await Db.InsertAsync<TD_OutStorRecord>(listtrecorddata);

                    //获取操作人的法人组织ID
                    var deptdata = await _opdept.GetOperatorDept();
                    //获取外协单ID ,和项目ID

                    var list1 = data1.GroupBy(x => new { x.OutsourcingBillId, x.OutsourcingCompanyId, x.ProjectId }).Select(x => new { OutsourcingBillId = x.Key.OutsourcingBillId, OutsourcingCompanyId = x.Key.OutsourcingCompanyId, ProjectId = x.Key.ProjectId }).FirstOrDefault();

                    //创建出库单
                    TD_OutStorage outdata = new TD_OutStorage();
                    outdata.Id = outid;
                    outdata.Code = DateTime.Now.ToString("yyyyMMddHHmmss");
                    outdata.OutTime = DateTime.Now;
                    outdata.StorageId = StorId;
                    outdata.OutType = "OutSourcing";
                    outdata.RefCode = list1.OutsourcingBillId;
                    outdata.ProjectId = list1.ProjectId;
                    outdata.CusId = list1.OutsourcingCompanyId;
                    //outdata.DesignId = PickUpMainProjectdata.DesignId;
                    outdata.OutNum = dbnum;
                    outdata.CreatorId = _operator.UserId;
                    outdata.CreateTime = DateTime.Now;
                    outdata.Deleted = false;
                    outdata.Status = 0;
                    outdata.QrCode = h_OutStorage + "," + outid;
                    outdata.DepId = deptdata.DetpId;
                    outdata.FactoryId = userdata.FactoryId;
                    await Db.InsertAsync<TD_OutStorage>(outdata);

                }
            }
            else
            {
                //出库单明细表
                List<TD_OutStorDetail> listdetaildata = new List<TD_OutStorDetail>();
                //仓库
                string StorId = string.Empty;
                //获区
                string AreaId = string.Empty;
                //货架
                string RackId = string.Empty;
                //出库单ID
                string outid = IdHelper.GetId();
                //定义数量
                double dbnum = 0;

                int i = 0;

                foreach (var item in dataList)
                {
                    if (i == 0)
                    {
                        //获取仓库,获区货架
                        var locadata = await Db.GetIQueryable<PB_Location>().Where(x => x.Id == item.LocalId).FirstOrDefaultAsync();
                        StorId = locadata.StorId;
                        AreaId = locadata.AreaId;
                        RackId = locadata.RackId;
                    }

                    TD_OutStorDetail outdetaildata = new TD_OutStorDetail();
                    outdetaildata.Id = IdHelper.GetId();
                    outdetaildata.StorId = StorId;
                    outdetaildata.OutStorId = outid;
                    outdetaildata.LocalId = item.LocalId;
                    outdetaildata.AreaId = AreaId;
                    outdetaildata.RackId = RackId;
                    outdetaildata.MaterialId = item.MaterialId;
                    outdetaildata.OutNum = Convert.ToDouble(item.PackNums);
                    outdetaildata.Price = Convert.ToDouble(item.Price);
                    outdetaildata.TotalAmt = Convert.ToDouble(item.PackNums) * Convert.ToDouble(item.Price);
                    dbnum += Convert.ToDouble(item.PackNums);
                    outdetaildata.CreatorId = _operator.UserId;
                    outdetaildata.CreateTime = DateTime.Now;
                    outdetaildata.Deleted = false;
                    listdetaildata.Add(outdetaildata);
                    i++;

                }
                await Db.InsertAsync<TD_OutStorDetail>(listdetaildata);
                //添加出库汇总明细表
                List<TD_OutStorRecord> listtrecorddata = new List<TD_OutStorRecord>();
                var listd = listdetaildata.GroupBy(x => new { x.StorId, x.LocalId, x.OutStorId, x.MaterialId, x.Price }).Select(x => new { StorId = x.Key.StorId, LocalId = x.Key.LocalId, OutStorId = x.Key.OutStorId, MaterialId = x.Key.MaterialId, Price = x.Key.Price, Nums = x.Sum(n => n.OutNum) });
                foreach (var item in listd)
                {
                    TD_OutStorRecord recodata = new TD_OutStorRecord();
                    recodata.Id = IdHelper.GetId();
                    recodata.StorId = item.StorId;
                    recodata.OutStorId = item.OutStorId;
                    recodata.MaterialId = item.MaterialId;
                    recodata.OutNum = item.Nums;
                    recodata.Price = item.Price;
                    recodata.TotalAmt = item.Nums * item.Price;
                    recodata.CreateTime = DateTime.Now;
                    recodata.CreatorId = _operator.UserId;
                    recodata.Deleted = false;
                    listtrecorddata.Add(recodata);
                }
                await Db.InsertAsync<TD_OutStorRecord>(listtrecorddata);

                //获取操作人的法人组织ID
                var deptdata = await _opdept.GetOperatorDept();
                //获取外协单ID ,和项目ID

                var list1 = dataList.GroupBy(x => new { x.OutsourcingBillId, x.OutsourcingCompanyId, x.ProjectId }).Select(x => new { OutsourcingBillId = x.Key.OutsourcingBillId, OutsourcingCompanyId = x.Key.OutsourcingCompanyId, ProjectId = x.Key.ProjectId }).FirstOrDefault();


                //创建出库单
                TD_OutStorage outdata = new TD_OutStorage();
                outdata.Id = outid;
                outdata.Code = DateTime.Now.ToString("yyyyMMddHHmmss");
                outdata.OutTime = DateTime.Now;
                outdata.StorageId = StorId;
                outdata.OutType = "OutSourcing";
                outdata.RefCode = list1.OutsourcingBillId;
                outdata.ProjectId = list1.ProjectId;
                outdata.CusId = list1.OutsourcingCompanyId;
                //outdata.DesignId = PickUpMainProjectdata.DesignId;
                outdata.OutNum = dbnum;
                outdata.CreatorId = _operator.UserId;
                outdata.CreateTime = DateTime.Now;
                outdata.Deleted = false;
                outdata.Status = 0;
                outdata.QrCode = h_OutStorage + "," + outid;
                outdata.DepId = deptdata.DetpId;
                outdata.FactoryId = userdata.FactoryId;
                await Db.InsertAsync<TD_OutStorage>(outdata);
            }

        }






        /// <summary>
        /// 外包回货装车
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [Transactional]
        public async Task AddBackTransportBillDetailAsync(PB_TransportBillDetailDTO data)
        {
            // ---------------------------------   变量 ------------------------------    
            string qrcodemodel = data.PackQrCode.Split(',')?[0].ToString();
            string packid = string.Empty;
            string materialId = string.Empty;
            if (qrcodemodel == "13")
                packid = data.PackQrCode.Split(',')[1].ToString();
            else
                throw new BusException("请扫描正确的二维码信息");


            // ------------------------------ 获取包信息 --------------------------------
            // 获取这个包
            var PackListdata = await Db.GetIQueryable<PB_PackList>().Where(x => x.Id == packid).FirstOrDefaultAsync();
            //获取车辆绑定得外包单ID
            var dataList = await Db.GetIQueryable<PB_TransportBill>().Where(x => x.DeliveryNoticeId == PackListdata.TaskId && x.BillType == "Outsourcing_I").FirstOrDefaultAsync();
            //获取包装数量
            Double PackNums = await Db.GetIQueryable<PB_PackListInfo>().Where(x => x.PackId == PackListdata.Id).CountAsync();
            if (dataList == null)
            {
                throw new BusException("该包与所需要装车的包信息不符!");
            }

            if (PackListdata != null)
            {
                //获取操作人的用户信息
                Base_User basedata = await Db.GetIQueryable<Base_User>().Where(x => x.Id == _operator.UserId).FirstOrDefaultAsync();
                // 查询派车单和对应的包
                var billdata = await Db.GetIQueryable<PB_TransportBillDetail>().Where(x => x.ParentId == data.BillId && x.PackId == packid).FirstOrDefaultAsync();
                if (billdata == null)
                {
                    //装车
                    PB_TransportBillDetail pbdata = new PB_TransportBillDetail();
                    pbdata.Id = IdHelper.GetId();
                    pbdata.ParentId = data.BillId;
                    //pbdata.DesignDetailId = packdata.subId;
                    //pbdata.PreparationNoteId = packdata.stockupId;
                    pbdata.PackId = packid;
                    pbdata.MaterialId = PackListdata.MaterialId;
                    pbdata.PretendCarUserId = _operator.UserId;
                    pbdata.PretendCarUserName = basedata.RealName;
                    pbdata.PretendCarTime = DateTime.Now;
                    pbdata.PackNums = PackNums;
                    pbdata.ReceiptQuantity = 0;
                    pbdata.CreatorId = _operator.UserId;
                    pbdata.CreatorName = basedata.RealName;
                    pbdata.CreateTime = DateTime.Now;
                    pbdata.Deleted = false;
                    pbdata.Status = 0;
                    await Db.InsertAsync(pbdata);

                    List<PB_TransportBillDetail> listdata = await Db.GetIQueryable<PB_TransportBillDetail>().Where(x => x.ParentId == data.BillId).ToListAsync();
                    if (listdata.Count == 1)
                    {
                        string sqlMain = @"update PB_TransportBill set LoadingStartTime='" + DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss") + "' where id='" + data.BillId + "'";
                        await ExecuteSqlAsync(sqlMain);
                    }
                }
                else
                {
                    throw new BusException("请勿扫描重复的包!");
                }
            }
            else
            {
                throw new BusException("请扫描正确的二维码信息");
            }


        }

        /// <summary>
        /// 外协回货车辆信息
        /// </summary>
        /// <param name="billType"></param>
        /// <returns></returns>
        public async Task<List<PB_TransportBillVehicleDTO>> GetInCarInformationAsync(string billType)
        {
            var deptdata = await _opdept.GetOperatorDeptType();

            Expression<Func<PB_TransportBill, PB_Vehicle, PB_OutsourcingBill, PB_TransportBillVehicleDTO>> select = (a, b, c) => new PB_TransportBillVehicleDTO
            {
                PlateName = b.PlateNO,
                SupplierId = c.OutsourcingCompanyId
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in Db.GetIQueryable<PB_TransportBill>().AsExpandable()
                    join b in Db.GetIQueryable<PB_Vehicle>() on a.Vehicle equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    join c in Db.GetIQueryable<PB_OutsourcingBill>() on a.DeliveryNoticeId equals c.Id into ac
                    from c in ac.DefaultIfEmpty()
                    select @select.Invoke(a, b, c);

            if (billType == "Outsourcing_I")
            {
                q = q.Where(x => x.State == 0 && x.BillType == billType && x.SupplierId == deptdata.SupplierId);
            }
            var res = await q.ToListAsync();
            if (res.Count > 0)
            {
                return res;
            }
            else
            {
                throw new BusException("暂无数据");
            }

        }

        /// <summary>
        /// 根据车牌获取回货车辆信息
        /// </summary>
        /// <param name="plateno">车牌</param>
        /// <param name="billType">车辆类型</param>
        /// <returns></returns>
        public async Task<PB_TransportBillDataDetailDTO> GetInTransportBillDataaAsync(string plateno, string billType)
        {
            var deptdata = await _opdept.GetOperatorDeptType();
            Expression<Func<PB_TransportBill, PB_Vehicle, PB_OutsourcingBill, PB_TransportBillDataDetailDTO>> selectdata = (a, b, c) => new PB_TransportBillDataDetailDTO
            {
                PlateName = b.PlateNO,
                SupplierId = c.OutsourcingCompanyId
            };
            selectdata = selectdata.BuildExtendSelectExpre();
            var q = from a in Db.GetIQueryable<PB_TransportBill>().AsExpandable()
                    join b in Db.GetIQueryable<PB_Vehicle>() on a.Vehicle equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    join c in Db.GetIQueryable<PB_OutsourcingBill>() on a.DeliveryNoticeId equals c.Id into ac
                    from c in ac.DefaultIfEmpty()
                    select @selectdata.Invoke(a, b, c);
            if (billType == "Outsourcing_I")
            {
                q = q.Where(x => x.State == 0 && x.BillType == billType && x.SupplierId == deptdata.SupplierId && x.PlateNO == plateno);
            }


            var qd = await q.FirstOrDefaultAsync();
            if (qd != null)
            {
                PB_TransportBillDataDetailDTO pbdata = new PB_TransportBillDataDetailDTO();
                pbdata.Id = qd.Id;
                pbdata.CreateTime = qd.CreateTime;
                pbdata.CreatorId = qd.CreatorId;
                pbdata.Deleted = qd.Deleted;
                //pbdata.DesignListid = q.DesignListid;
                //pbdata.DispatchBillid = q.DispatchBillid;
                //pbdata.PickingBillid = q.PickingBillid;
                pbdata.DeliveryNoticeId = qd.DeliveryNoticeId;
                pbdata.Vehicle = qd.Vehicle;
                pbdata.SendTime = qd.SendTime;
                pbdata.IntoTime = qd.IntoTime;
                pbdata.DeliveryTime = qd.DeliveryTime;
                pbdata.Tunnage = qd.Tunnage;
                pbdata.DocumentMaker = qd.DocumentMaker;
                pbdata.EmptyNumber = qd.EmptyNumber;
                pbdata.EmptyTime = qd.EmptyTime;
                pbdata.NetloadNumber = qd.NetloadNumber;
                pbdata.RoughweightNumber = qd.RoughweightNumber;
                pbdata.RoughweightTime = qd.RoughweightTime;
                pbdata.WeighingPeople = qd.WeighingPeople;
                pbdata.DepartureTime = qd.DepartureTime;
                pbdata.State = qd.State;
                pbdata.DriverName = qd.DriverName;
                pbdata.Iphone = qd.Iphone;
                pbdata.PlateNO = qd.PlateNO;
                pbdata.PlateName = qd.PlateName;
                pbdata.VehicleLicense = qd.VehicleLicense;
                pbdata.DrivingLicense = qd.DrivingLicense;
                pbdata.Estimatedweight = qd.Estimatedweight;
                pbdata.EnteringPlantMan = qd.EnteringPlantMan;
                pbdata.ExFactoryMan = qd.ExFactoryMan;

                string sqlMain = @"select *,ROW_NUMBER() over(order by CreateTime desc) as rowsid from ( SELECT a.Id,a.PackId,a.MaterialId,a.PackNums as Nums,b.BoxName as PackName,c.Spec as MaterialSpec,a.CreateTime FROM PB_TransportBillDetail as a join PB_PackList as b on a.PackId=b.Id join PB_Material as c on a.MaterialId=c.Id where a.ParentId='" + qd.Id + "' and b.PackageType=0 UNION ALL select '' as Id,PackId,'' as MaterialId,SUM(Nums) as Nums,PackName,'' as MaterialSpec,CreateTime from ( SELECT a.PackId,b.BoxName as PackName,a.PackNums as Nums,DATE_FORMAT(a.CreateTime,'%Y-%m-%d') as CreateTime FROM PB_TransportBillDetail as a join PB_PackList as b on a.PackId=b.Id join PB_Material as c on a.MaterialId=c.Id where a.ParentId='" + qd.Id + "' and b.PackageType=1 ) as t group by PackId,PackName,CreateTime UNION ALL select a.Id,a.PackId,a.MaterialId,a.PackNums as Nums,b.`Name` as PackName,b.Spec as MaterialSpec,a.CreateTime from PB_TransportBillDetail as a join PB_Material as b on a.MaterialId=b.Id where a.ParentId='" + qd.Id + "' and a.PackId='' ) as t";
                var transportbilldetail = await Db.GetListBySqlAsync<PB_TransportBillDetailListData>(sqlMain);
                pbdata.TransportBillDetail = transportbilldetail;
                return pbdata;
            }
            else
            {
                throw new BusException("请核对车辆信息");
            }

        }
        /// <summary>
        /// 卸车获取车辆信息
        /// </summary>
        /// <param name="plateno"></param>
        /// <param name="deptId"></param>
        /// <param name="billType"></param>
        /// <returns></returns>
        public async Task<PB_TransportBillDataDetailDTO> GetInOutTransportBillDataAsync(string plateno, string deptId, string billType)
        {
            //获取登录人法人一级组织信息
            var dpdata = await _opdept.GetOperatorDept();
            List<string> liststr = new List<string>();
            liststr.Add(dpdata.DetpId);
            //获取所有的部门信息
            List<Base_Department> deptlist = await Db.GetIQueryable<Base_Department>().ToListAsync();
            var listdata = deptlist.Where(x => x.ParentId == dpdata.DetpId).ToList();
            foreach (var item in listdata)
            {
                liststr.Add(item.Id);
                GetDeptItem(item.Id, liststr, deptlist);
            }
            //var q = await Db.GetIQueryable<PB_TransportBill>().Where(x => liststr.Contains(x.DeptId) && x.State == 1 && x.BillType == 0 && x.PlateNO == plateno).FirstOrDefaultAsync();
            Expression<Func<PB_TransportBill, PB_Vehicle, PB_TransportBillDataDetailDTO>> selectdata = (a, b) => new PB_TransportBillDataDetailDTO
            {
                PlateName = b.PlateNO
            };
            selectdata = selectdata.BuildExtendSelectExpre();
            var q = from a in Db.GetIQueryable<PB_TransportBill>().AsExpandable()
                    join b in Db.GetIQueryable<PB_Vehicle>() on a.Vehicle equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    select @selectdata.Invoke(a, b);


            if (billType == "Outsourcing_O")
            {
                q = q.Where(x => liststr.Contains(x.DeptId) && (x.State == 1) && x.BillType == billType && x.PlateName == plateno);
            }
            else if (billType == "Outsourcing_I")
            {
                q = q.Where(x => liststr.Contains(x.DeptId) && (x.State == 1) && x.BillType == billType && x.PlateName == plateno);
            }
            else
            {
                q = q.Where(x => liststr.Contains(x.DeptId) && (x.State == 0) && x.BillType == billType && x.PlateName == plateno);
            }
            var qd = await q.FirstOrDefaultAsync();
            if (qd != null)
            {
                PB_TransportBillDataDetailDTO pbdata = new PB_TransportBillDataDetailDTO();
                pbdata.Id = qd.Id;
                pbdata.CreateTime = qd.CreateTime;
                pbdata.CreatorId = qd.CreatorId;
                pbdata.Deleted = qd.Deleted;
                pbdata.DeliveryNoticeId = qd.DeliveryNoticeId;
                pbdata.Vehicle = qd.Vehicle;
                pbdata.SendTime = qd.SendTime;
                pbdata.IntoTime = qd.IntoTime;
                pbdata.DeliveryTime = qd.DeliveryTime;
                pbdata.Tunnage = qd.Tunnage;
                pbdata.DocumentMaker = qd.DocumentMaker;
                pbdata.EmptyNumber = qd.EmptyNumber;
                pbdata.EmptyTime = qd.EmptyTime;
                pbdata.NetloadNumber = qd.NetloadNumber;
                pbdata.RoughweightNumber = qd.RoughweightNumber;
                pbdata.RoughweightTime = qd.RoughweightTime;
                pbdata.WeighingPeople = qd.WeighingPeople;
                pbdata.DepartureTime = qd.DepartureTime;
                pbdata.State = qd.State;
                pbdata.DriverName = qd.DriverName;
                pbdata.Iphone = qd.Iphone;
                pbdata.PlateNO = qd.PlateNO;
                pbdata.PlateName = qd.PlateName;
                pbdata.VehicleLicense = qd.VehicleLicense;
                pbdata.DrivingLicense = qd.DrivingLicense;
                pbdata.Estimatedweight = qd.Estimatedweight;
                pbdata.EnteringPlantMan = qd.EnteringPlantMan;
                pbdata.ExFactoryMan = qd.ExFactoryMan;
                pbdata.QrCode = qd.QrCode;
                return pbdata;
            }
            else
            {
                throw new BusException("请核对车辆信息");
            }
        }

        /// <summary>
        /// 项目回货选择回货车辆
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public async Task<List<ProjectReturnSelection>> GetTransportBillReturnId(string Id)
        {
            string sql = "SELECT b.PlateNO,a.Id Id FROM PB_TransportBill AS a LEFT JOIN PB_Vehicle AS b on a.Vehicle = b.Id LEFT JOIN PB_TransportBillGroup AS g ON g .ParentId=a.Id WHERE g.DeliveryNoticeId = '" + Id + "'  AND a.State=0 	and a.BillType='Return'";
            var list = await Db.GetListBySqlAsync<ProjectReturnSelection>(sql);
            return list;
        }

        public async Task<PB_TransportBillDTO> GetDingBillListDataAsync(string ProjectId, string billqrcode)
        {
            var projectLike = $"SELECT b.Id AS DeliveryNoticeId,b.ProjectId,b.ProjectName FROM PB_TransportBillGroup AS a  JOIN PB_DeliveryNotice AS b ON a.DeliveryNoticeId = b.Id WHERE a.ParentId = '{billqrcode.Split(',')[1].ToString()}'  AND b.ProjectId='{ProjectId}'  GROUP BY b.Id,b.ProjectId,b.ProjectName";
            var list = await Db.GetListBySqlAsync<BillProjectDTO>(projectLike);
            if (list.Count <= 0)
            {
                throw new BusException("请扫描当前项目下的派车单!");
            }
            var q = await Db.GetIQueryable<PB_TransportBill>().Where(x => x.Id == billqrcode.Split(',')[1].ToString()).FirstOrDefaultAsync();
            if (q != null)
            {
                if (q.State == 5)
                {
                    throw new BusException("已验收");
                }
                else if (q.BillType == "Outsourcing_I" && q.State == 1)
                {
                    var cedata = await Db.GetIQueryable<PB_Vehicle>().Where(x => x.Id == q.Vehicle).FirstOrDefaultAsync();
                    PB_TransportBillDTO pbdata = new PB_TransportBillDTO();
                    pbdata.Id = q.Id;
                    pbdata.CreateTime = q.CreateTime;
                    pbdata.CreatorId = q.CreatorId;
                    pbdata.Deleted = q.Deleted;
                    pbdata.Vehicle = q.Vehicle;
                    pbdata.SendTime = q.SendTime;
                    pbdata.IntoTime = q.IntoTime;
                    pbdata.DeliveryTime = q.DeliveryTime;
                    pbdata.Tunnage = q.Tunnage;
                    pbdata.DocumentMaker = q.DocumentMaker;
                    pbdata.EmptyNumber = q.EmptyNumber;
                    pbdata.EmptyTime = q.EmptyTime;
                    pbdata.NetloadNumber = q.NetloadNumber;
                    pbdata.RoughweightNumber = q.RoughweightNumber;
                    pbdata.RoughweightTime = q.RoughweightTime;
                    pbdata.WeighingPeople = q.WeighingPeople;
                    pbdata.DepartureTime = q.DepartureTime;
                    pbdata.State = q.State;
                    pbdata.DriverName = q.DriverName;
                    pbdata.Iphone = q.Iphone;
                    pbdata.PlateNO = cedata.PlateNO;
                    pbdata.VehicleLicense = q.VehicleLicense;
                    pbdata.DrivingLicense = q.DrivingLicense;
                    pbdata.Estimatedweight = q.Estimatedweight;
                    pbdata.EnteringPlantMan = q.EnteringPlantMan;
                    pbdata.ExFactoryMan = q.ExFactoryMan;
                    pbdata.QrCode = q.QrCode;
                    Expression<Func<PB_TransportBillDetail, PB_PackList, PB_TransportBillDetailDataDTO>> select = (a, b) => new PB_TransportBillDetailDataDTO
                    {
                        PackName = b.BoxName
                    };
                    select = select.BuildExtendSelectExpre();
                    var qdata = from a in Db.GetIQueryable<PB_TransportBillDetail>().AsExpandable()
                                join b in Db.GetIQueryable<PB_PackList>() on a.PackId equals b.Id into ab
                                from b in ab.DefaultIfEmpty()
                                select @select.Invoke(a, b);
                    qdata = qdata.Where(x => x.ParentId == q.Id && x.Status == 1).OrderByDescending(x => x.CreateTime);
                    pbdata.TransportBillDetail = await qdata.ToListAsync();
                    pbdata.TransportBillImg = await Db.GetIQueryable<PB_TransportBillImg>().Where(x => x.BillId == q.Id).ToListAsync();
                    return pbdata;
                }
                else
                {
                    if (q.State == 4)
                    {
                        var cedata = await Db.GetIQueryable<PB_Vehicle>().Where(x => x.Id == q.Vehicle).FirstOrDefaultAsync();
                        PB_TransportBillDTO pbdata = new PB_TransportBillDTO();
                        pbdata.Id = q.Id;
                        pbdata.CreateTime = q.CreateTime;
                        pbdata.CreatorId = q.CreatorId;
                        pbdata.Deleted = q.Deleted;
                        pbdata.Vehicle = q.Vehicle;
                        pbdata.SendTime = q.SendTime;
                        pbdata.IntoTime = q.IntoTime;
                        pbdata.DeliveryTime = q.DeliveryTime;
                        pbdata.Tunnage = q.Tunnage;
                        pbdata.DocumentMaker = q.DocumentMaker;
                        pbdata.EmptyNumber = q.EmptyNumber;
                        pbdata.EmptyTime = q.EmptyTime;
                        pbdata.NetloadNumber = q.NetloadNumber;
                        pbdata.RoughweightNumber = q.RoughweightNumber;
                        pbdata.RoughweightTime = q.RoughweightTime;
                        pbdata.WeighingPeople = q.WeighingPeople;
                        pbdata.DepartureTime = q.DepartureTime;
                        pbdata.State = q.State;
                        pbdata.DriverName = q.DriverName;
                        pbdata.Iphone = q.Iphone;
                        pbdata.PlateNO = cedata.PlateNO;
                        pbdata.VehicleLicense = q.VehicleLicense;
                        pbdata.DrivingLicense = q.DrivingLicense;
                        pbdata.Estimatedweight = q.Estimatedweight;
                        pbdata.EnteringPlantMan = q.EnteringPlantMan;
                        pbdata.ExFactoryMan = q.ExFactoryMan;
                        pbdata.QrCode = q.QrCode;
                        Expression<Func<PB_TransportBillDetail, PB_PackList, PB_TransportBillDetailDataDTO>> select = (a, b) => new PB_TransportBillDetailDataDTO
                        {
                            PackName = b.BoxName
                        };
                        select = select.BuildExtendSelectExpre();
                        var qdata = from a in Db.GetIQueryable<PB_TransportBillDetail>().AsExpandable()
                                    join b in Db.GetIQueryable<PB_PackList>() on a.PackId equals b.Id into ab
                                    from b in ab.DefaultIfEmpty()
                                    select @select.Invoke(a, b);
                        qdata = qdata.Where(x => x.ParentId == q.Id && x.Status == 1).OrderByDescending(x => x.CreateTime);
                        pbdata.TransportBillDetail = await qdata.ToListAsync();
                        pbdata.TransportBillImg = await Db.GetIQueryable<PB_TransportBillImg>().Where(x => x.BillId == q.Id).ToListAsync();

                        // 获取派车单对应的项目信息
                        string sqlMain = @"select b.Id as DeliveryNoticeId,b.ProjectId,b.ProjectName from PB_TransportBillGroup as a join PB_DeliveryNotice as b on a.DeliveryNoticeId=b.Id where a.ParentId='" + q.Id + "'group by b.Id,b.ProjectId,b.ProjectName";
                        pbdata.ProjectList = await Db.GetListBySqlAsync<BillProjectDTO>(sqlMain);
                        return pbdata;
                    }
                    else
                    {
                        throw new BusException("暂无验收车辆信息");
                    }
                }
            }
            else
            {
                throw new BusException("请核对车辆信息");
            }
        }

        /// <summary>
        /// 钉钉项目收货卸车提交
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task CheckDingBillDTO(DingBillDTO data)
        {
            string billId = data.billqrcode.Split(',')?[1].ToString();
            string   sqlMain = "update PB_TransportBill set State=5,AcceptanceTime=NOW(),ReceivingRemarks='" + data.ReceivingRemarks + "' where Id='" + billId + "'";
             await ExecuteSqlAsync(sqlMain);
        }

        public async Task<PageResult<DingTransportBillModel>> GetDingTransportBillModel(PageInput<DingTransportBillSearch> input)
        {
            string sql = @"SELECT
	t.BillId,
	t.PlateNo,
	t.AcceptanceTime,
	t.ReceivingRemarks,
	t.NoticeID,
	o.*,
CASE
		
		WHEN t.State > 4 THEN
		1 
		WHEN o.ReceivingNums >= PackNums THEN
		1 ELSE 0 
	END state 
FROM
	(
	SELECT
		Bill.ID 'BillId',
		Vehicle.PlateNO 'PlateNo',
		Bill.AcceptanceTime 'AcceptanceTime',
		Bill.ReceivingRemarks 'ReceivingRemarks',
		Notice.ID NoticeID,
		Bill.State 'State' 
	FROM
		PB_TransportBillGroup AS Grouprs
		LEFT JOIN PB_TransportBill AS Bill ON Grouprs.ParentId = Bill.Id
		LEFT JOIN PB_DeliveryNotice AS Notice ON Grouprs.DeliveryNoticeId = Notice.Id
		LEFT JOIN PB_Vehicle AS Vehicle ON Bill.Vehicle = Vehicle.Id 
	WHERE
		Bill.State > 3 
		AND Notice.ProjectId = '" + input.Search.ProjectId + "' GROUP BY Bill.ID,Notice.Id ORDER BY	Bill.DepartureTime DESC ) AS t INNER  JOIN (SELECT  detail.ParentId,SUM(detail.PackNums) AS PackNums,  SUM(list.ReceivingNums) AS ReceivingNums, Notice.Id AS ItemParentid FROM PB_TransportBillDetail AS detail    LEFT JOIN PB_PickUpMain AS  Main ON detail.PreparationNoteId = Main.Id  LEFT JOIN PB_DeliveryNoticeItem as item on Main.ParentId = item.Id  LEFT JOIN PB_DeliveryNotice as Notice on item.ParentId = Notice.Id  LEFT JOIN PB_TransportBillDetailList AS list on list.BillDetailId = detail.Id LEFT JOIN PB_DesignList AS Design on item.DesignId = Design.Id    WHERE Design.BuildingNumberID = '" + input.Search.Bulid + "'  GROUP BY  detail.ParentId,	Notice.Id ) AS o ON o.ItemParentid = t.NoticeID AND o.ParentId=t.BillId   UNION all  SELECT  t.BillId,	t.PlateNo,	t.AcceptanceTime,t.ReceivingRemarks,t.NoticeID,o.*, CASE  WHEN t.State > 4 THEN 1  WHEN o.ReceivingNums >= PackNums THEN   1 ELSE 0 END state FROM (  SELECT  Bill.ID 'BillId', Vehicle.PlateNO 'PlateNo',Bill.AcceptanceTime 'AcceptanceTime', Bill.ReceivingRemarks 'ReceivingRemarks', Notice.ID NoticeID,    Bill.State 'State' FROM PB_TransportBillGroup AS Grouprs  LEFT JOIN PB_TransportBill AS Bill ON Grouprs.ParentId = Bill.Id  LEFT JOIN PB_DeliveryNotice AS Notice ON Grouprs.DeliveryNoticeId = Notice.Id LEFT JOIN PB_Vehicle AS Vehicle ON Bill.Vehicle = Vehicle.Id  WHERE  Bill.State > 3   AND Notice.ProjectId = '" + input.Search.ProjectId + "' GROUP BY    Bill.ID,  Notice.Id ORDER BY  Bill.DepartureTime DESC ) AS t INNER JOIN( SELECT  detail.ParentId,   SUM(detail.PackNums ) AS PackNums, SUM(lists.ReceivingNums ) AS ReceivingNums,  Notice.Id AS ItemParentid   FROM PB_TransportBillDetail AS detail LEFT JOIN PB_PickUpList AS List ON detail.PreparationNoteId = List.Id LEFT JOIN PB_PickUpMain AS Main ON List.ParentId = Main.Id  LEFT JOIN PB_DeliveryNoticeItem AS item ON Main.ParentId = item.Id  LEFT JOIN PB_DeliveryNotice AS Notice ON item.ParentId = Notice.Id   LEFT JOIN PB_TransportBillDetailList AS lists ON lists.BillDetailId = detail.Id LEFT JOIN PB_DesignList AS Design ON item.DesignId = Design.Id WHERE    Design.BuildingNumberID = '" + input.Search.Bulid + "' GROUP BY detail.ParentId,  Notice.Id) AS o ON o.ItemParentid = t.NoticeID AND o.ParentId = t.BillId ";
            var res = await Db.GetListBySqlAsync<DingTransportBillModel>(sql);
            int pagecount;//总页数
            List<DingTransportBillModel> listpro_down = res.ToList();//一个要分页的，类型数据集合，存储的是所有的数据
            List<DingTransportBillModel> productes = new List<DingTransportBillModel>();//用来存储要展示的数据
            int pagees = listpro_down.Count;//所有数据的总条数
                                            //计算总页数
            if (pagees % input.PageRows == 0)
            {
                pagecount = pagees / input.PageRows;
            }
            else
            {
                pagecount = (pagees / input.PageRows) + 1;
            }
            productes = listpro_down.Skip((input.PageIndex - 1) * input.PageRows).Take(input.PageRows).ToList();//分页的重点
            return new PageResult<DingTransportBillModel> { Data = productes, Total = pagees };
        }

        public async Task<PageResult<PB_ProjectDelivery>> GetProjectDeliveryList(PageInput<DingTransportBillSearch> input)
        {
            StringBuilder sql = new StringBuilder();

            sql.AppendLine(" SELECT");
            sql.AppendLine(" c.ID BillId,");
            sql.AppendLine(" b.Abstract,");
            sql.AppendLine(" case when c.State >= 4 then '已发货' else '未发货' end State,");
            sql.AppendLine(" c.PlateNO,");
            sql.AppendLine(" d.OutNum,");
            sql.AppendLine(" Date(c.DepartureTime) DepartureTime,");
            sql.AppendLine(" case when e.BillId is null then '未收货' else '已收货' end GetState,");
            sql.AppendLine(" e.GetNum");
            sql.AppendLine(" FROM");
            sql.AppendLine(" PB_TransportBillGroup a");
            sql.AppendLine(" LEFT JOIN PB_DeliveryNotice b ON a.DeliveryNoticeId = b.Id");
            sql.AppendLine(" LEFT JOIN PB_TransportBill c ON a.ParentId = c.Id");
            sql.AppendLine(" left join(select sum(PackNums) OutNum, ParentId from PB_TransportBillDetail group by ParentId) d on c.Id = d.ParentId");
            sql.AppendLine(" left join(select BillId, IFNULL(sum(Nums),0)  GetNum from pb_tranrecevingdetail group by BillId) e on c.Id = e.BillId");
            sql.AppendLine(" WHERE c.BillType = 'Delivery'");
            if (!input.Search.ProjectName.IsNullOrEmpty())
            {
                sql.AppendLine("And b.Abstract like '%" + input.Search.ProjectName + "%'");
            }
            if (!input.Search.StartDate.IsNullOrEmpty() && !input.Search.EndDate.IsNullOrEmpty())
            {
                sql.AppendLine("AND c.DepartureTime between    '" + Convert.ToDateTime(input.Search.StartDate).ToString("yyyy-MM-dd 00:00:00") + "' and '" + Convert.ToDateTime(input.Search.EndDate).ToString("yyyy-MM-dd 23:59:59") + " '");
            }
            sql.AppendLine("ORDER BY  Date(c.DepartureTime) DESC");
            var res = await Db.GetListBySqlAsync<PB_ProjectDelivery>(sql.ToString());
            int pagecount;//总页数
            List<PB_ProjectDelivery> listpro_down = res.ToList();//一个要分页的，类型数据集合，存储的是所有的数据
            List<PB_ProjectDelivery> productes = new List<PB_ProjectDelivery>();//用来存储要展示的数据
            int pagees = listpro_down.Count;//所有数据的总条数
                                            //计算总页数
            if (pagees % input.PageRows == 0)
            {
                pagecount = pagees / input.PageRows;
            }
            else
            {
                pagecount = (pagees / input.PageRows) + 1;
            }
            productes = listpro_down.Skip((input.PageIndex - 1) * input.PageRows).Take(input.PageRows).ToList();//分页的重点
            return new PageResult<PB_ProjectDelivery> { Data = productes, Total = pagees };



        }
        /// <summary>
        ///现场收货扫成品码
        /// </summary>
        /// <param name="billqrcode">派车单编号</param>
        /// <param name="Jobcode">成品二维码</param>
        /// <returns></returns>
        public async Task UnloadScanfinished(string billqrcode, string Jobcode)
        {
            string billId = billqrcode.Split(',')?[1].ToString();
            string JobId = Jobcode.Split(',')?[1].ToString();
            Base_User userdata = await Db.GetIQueryable<Base_User>().Where(x => x.Id == _operator.UserId).FirstOrDefaultAsync();
            PB_TransportBillDetail pbdata = await Db.GetIQueryable<PB_TransportBillDetail>().Where(x => x.ParentId == billId && x.JobId == JobId).FirstOrDefaultAsync();
            if (pbdata != null)
            {

                ReceivingRemarksDTO rrdata = new ReceivingRemarksDTO
                {
                    BillDetailId = pbdata.Id,
                    //ProjectId = data.ProjectId,
                    MaterialId = pbdata.MaterialId,
                    ReceivingUserId = _operator.UserId,
                    ReceivingUserName = userdata.RealName,
                    ReceivingTime = DateTime.Now,
                    ReceivingNums = pbdata.PackNums
                };
                PB_TransportBillDetail dtdat = new PB_TransportBillDetail
                {
                    Id = pbdata.Id,
                    Status = 1,
                    ReceiptQuantity = pbdata.PackNums,
                    ReceivingRemarks = rrdata.ToJson(),
                    CreateTime = pbdata.CreateTime
                };
                List<string> props = GetFieldList<PB_TransportBillDetail>(dtdat);
                await Db.UpdateAsync<PB_TransportBillDetail>(dtdat, props);

                PB_TransportBillDetailList DetailList = new PB_TransportBillDetailList();
                DetailList.Id = IdHelper.GetId();
                DetailList.BillId = billId;
                DetailList.BillDetailId = pbdata.Id;

                DetailList.MaterialId = pbdata.MaterialId;
                DetailList.ReceivingUserId = _operator.UserId;
                DetailList.ReceivingUserName = userdata.RealName;
                DetailList.ReceivingTime = DateTime.Now;
                DetailList.ReceivingNums = pbdata.PackNums;
                DetailList.Status = 0;
                await Db.InsertAsync<PB_TransportBillDetailList>(DetailList);

            }
        }
        public async Task<List<PB_designremaks>> Getdesignremaks(string id)
        {
            //StringBuilder sql = new StringBuilder();
            //sql.AppendLine("SELECT");
            //sql.AppendLine("b.MaterialId,");
            //sql.AppendLine("m.`Name`,");
            //sql.AppendLine("a.Id ,");
            //sql.AppendLine("b.DesignDetailId,");
            //sql.AppendLine("n.Id NId,");
            //sql.AppendLine("item.Id itemId");
            //sql.AppendLine("FROM");
            //sql.AppendLine("PB_TransportBill AS a");
            //sql.AppendLine("LEFT JOIN PB_TransportBillDetail AS b ON a.Id = b.ParentId");
            //sql.AppendLine("LEFT JOIN PB_TransportBillGroup AS E ON E.ParentId = a.Id");
            //sql.AppendLine("LEFT JOIN PB_DeliveryNotice AS n on E.DeliveryNoticeId = n.Id");
            //sql.AppendLine("LEFT JOIN PB_DeliveryNoticeItem AS item on n.Id = item.ParentId");
            //sql.AppendLine("LEFT JOIN PB_DesignList AS list on item.DesignId = list.Id");
            //sql.AppendLine("LEFT JOIN PB_DesignDetail AS c ON b.DesignDetailId = c.Id");
            //sql.AppendLine("AND c.ParentId=list.Id");
            //sql.AppendLine("LEFT JOIN PB_Material AS m ON b.MaterialId = m.Id");
            //sql.AppendLine("WHERE");
            //sql.AppendLine("b.ParentId = '" + id + "'");
            //sql.AppendLine("AND b.MaterialId = c.MaterialId  AND (c.ParentId != list.Id)");
            string sql = $@"select detail.MaterialId,m.`Name` from PB_TransportBillGroup as a
left join pb_transportbilldetail as detail on a.ParentId=detail.ParentId
left join PB_DeliveryNoticeItem as b on a.DeliveryNoticeId=b.ParentId
left join PB_DesignDetail as c on detail.DesignDetailId=c.Id and c.ParentId=b.DesignId
LEFT JOIN PB_Material AS m ON detail.MaterialId = m.Id
where a.ParentId='{id}' AND detail.MaterialId=c.MaterialId AND c.ParentId!=b.DesignId group by detail.MaterialId,m.`Name`";
            var res = await Db.GetListBySqlAsync<PB_designremaks>(sql.ToString());
            return res;

        }

        public async Task<List<PB_pickListNumsremarks>> GetpickListNumsremarks(string id)
        {
            StringBuilder sql = new StringBuilder();
            sql.AppendLine(" SELECT ");
            sql.AppendLine(" IFNULL(sum(PickUpList.ReadyNums), 0) PreparedNums,");
            sql.AppendLine("  IFNULL(SUM(detail.PackNums), 0) AS LoadingNums,");
            sql.AppendLine("  m.`Name`,");
            sql.AppendLine("   detail.ParentId");
            sql.AppendLine("  FROM");
            sql.AppendLine("   PB_TransportBillDetail AS detail");
            sql.AppendLine(" LEFT JOIN PB_PickUpList AS PickUpList ON detail.PreparationNoteId = PickUpList.Id");
            sql.AppendLine("   LEFT JOIN PB_Material AS m on  detail.MaterialId = m.Id");
            sql.AppendLine("  WHERE detail.ParentId = '" + id + "'");
            sql.AppendLine("  GROUP BY");
            sql.AppendLine("   detail.ParentId ,detail.MaterialId");
            sql.AppendLine("   HAVING   SUM(detail.PackNums) > sum(PickUpList.ReadyNums)");
            var res = await Db.GetListBySqlAsync<PB_pickListNumsremarks>(sql.ToString());
            return res;

        }
        public async Task<List<PB_PickListWeightRemakrs>> GetPickListWeightRemakrs(string id)
        {
            StringBuilder sql = new StringBuilder();
            sql.AppendLine(" SELECT ");
            sql.AppendLine("  IFNULL(sum(PickUpList.ReadyNums * o.Weight), 0) PreparedNums, ");
            sql.AppendLine(" IFNULL(SUM(detail.PackNums * m.Weight), 0) AS LoadingNums, ");
            sql.AppendLine("m.`Name`, ");
            sql.AppendLine("detail.ParentId ");
            sql.AppendLine("FROM ");
            sql.AppendLine("  PB_TransportBillDetail AS detail ");
            sql.AppendLine(" LEFT JOIN PB_PickUpList AS PickUpList ON detail.PreparationNoteId = PickUpList.Id ");
            sql.AppendLine("LEFT JOIN PB_Material AS m ON detail.MaterialId = m.Id ");
            sql.AppendLine(" LEFT JOIN PB_Material AS o ON PickUpList.MaterialId = o.Id ");
            sql.AppendLine("WHERE ");
            sql.AppendLine(" detail.ParentId = '" + id + "' ");
            sql.AppendLine("GROUP BY ");
            sql.AppendLine("detail.ParentId, ");
            sql.AppendLine(" detail.MaterialId ");
            sql.AppendLine("HAVING ");
            sql.AppendLine("SUM(detail.PackNums) > sum(PickUpList.ReadyNums)");
            var res = await Db.GetListBySqlAsync<PB_PickListWeightRemakrs>(sql.ToString());
            return res;
        }
        public async Task<PB_ChecklistDto> GetChecklist(string id)
        {
            PB_ChecklistDto pB_ChecklistDto = new PB_ChecklistDto();
            var aa = await Db.GetIQueryable<PB_TransportBill>().Where(m => m.Id == id).FirstOrDefaultAsync();
            var designlist = await Getdesignremaks(id);
            var GetpickList = await GetpickListNumsremarks(id);
            var GetPickListWeight = await GetPickListWeightRemakrs(id);
            if (designlist.Count > 0)
            {
                String Remakes = "";
                foreach (var item in designlist)
                {
                    Remakes += item.Name + ",";
                    pB_ChecklistDto.PB_DesignListRemakrs = Remakes;
                }
                string update = "update PB_TransportBill set  InventoryErrRemarks='" + Remakes + "',InventoryErrStatus=true where id='" + id + "'";
                await Db.ExecuteSqlAsync(update);
            }
            else
            {
                pB_ChecklistDto.PB_DesignListRemakrs = "";
            }
            if (GetpickList.Count > 0)
            {
                String Remakes = "";
                foreach (var item in GetpickList)
                {

                    Remakes += item.Name + ",";
                    pB_ChecklistDto.PB_PickListNumsRemakrs = Remakes;
                }
                string update = "update PB_TransportBill set  StockUpErrRemarks='" + Remakes + "',StockUpErrStatus=true where id='" + id + "'";
                await Db.ExecuteSqlAsync(update);
            }
            else
            {
                pB_ChecklistDto.PB_PickListNumsRemakrs = "";
            }
            if (GetPickListWeight.Count > 0)
            {
                String Remakes = "";
                foreach (var item in GetPickListWeight)
                {
                    Remakes += item.Name + ",";
                    pB_ChecklistDto.PB_PickListWeightRemakrs = Remakes;
                }
                string update = "update PB_TransportBill set  WeightErrRemarks='" + Remakes + "',WeightErrStatus=true where id='" + id + "'";
                await Db.ExecuteSqlAsync(update);
            }
            else
            {
                pB_ChecklistDto.PB_PickListWeightRemakrs = "";
            }
            pB_ChecklistDto.PB_PickListWeightRemakrs = aa.WeightErrRemarks;

            return pB_ChecklistDto;
        }

        //钉钉查看装车单明细
        public async Task<List<See_TransportBill>> GetSee_TransportBillList(string id)
        {
            StringBuilder sql = new StringBuilder();

            sql.AppendLine("SELECT T.*,");
            sql.AppendLine("CASE");
            sql.AppendLine("WHEN T.ReceivingNums > 0 THEN");
            sql.AppendLine("'已卸车'");
            sql.AppendLine("ELSE");
            sql.AppendLine(" '未卸车'");
            sql.AppendLine(" END 'states',");
            sql.AppendLine("CASE WHEN T.PackId  !=''  THEN  CONCAT('包:', T.PackId)  WHEN T.JobId != '' THEN  CONCAT('成品:', T.JobId)    ELSE CONCAT('单个物料:', T.MaterialId)  END 'type'");
            sql.AppendLine("FROM(");
            sql.AppendLine("SELECT");
            sql.AppendLine("M.`Code`,");
            sql.AppendLine("M.`Name`,");
            sql.AppendLine("M.Spec,");
            sql.AppendLine("a.PackNums,");
            sql.AppendLine("IFNULL(sum(b.ReceivingNums), 0) ReceivingNums,");
            sql.AppendLine("project.Id ProjectId,");
            sql.AppendLine("Building.Id BuildingId,");
            sql.AppendLine("project.`Name` ProjectName,");
            sql.AppendLine("Building.Buildingnumber,");
            sql.AppendLine("a.PackId AS PackId,");
            sql.AppendLine("a.JobId,");
            sql.AppendLine("a.MaterialId,");
            sql.AppendLine("notice.Abstract");
            sql.AppendLine("FROM");
            sql.AppendLine("PB_TransportBillDetail AS a");
            sql.AppendLine("LEFT JOIN PB_TransportBillDetailList AS b ON b.BillDetailId = a.Id");
            sql.AppendLine("LEFT JOIN PB_Material AS M ON a.MaterialId = M.Id");
            sql.AppendLine("LEFT JOIN PB_PickUpList AS PickList ON a.PreparationNoteId = PickList.Id");
            sql.AppendLine("LEFT JOIN PB_PickUpMain AS Main ON PickList.ParentId = Main.Id");
            sql.AppendLine("LEFT JOIN PB_DeliveryNoticeItem AS Item ON  Main.ParentId = Item.Id");
            sql.AppendLine("LEFT JOIN PB_DeliveryNotice AS notice on Item.ParentId = notice.Id");
            sql.AppendLine("LEFT JOIN PB_DesignList AS  Design  on Item.DesignId = Design.Id");
            sql.AppendLine("LEFT JOIN PB_Project AS project ON  notice.ProjectId = project.Id");
            sql.AppendLine("LEFT JOIN PB_Buildingnumber AS Building ON  Design.BuildingNumberID = Building.Id");
            sql.AppendLine(" WHERE");
            sql.AppendLine("  a.ParentId = '" + id + "'  	group by a.Id");
            sql.AppendLine(" ) AS T    ORDER BY   T.ProjectName,T.Buildingnumber");
            var listData = await Db.GetListBySqlAsync<See_TransportBill>(sql.ToString());
            return listData;
        }
        public async Task<List<See_TransportBill>> GetSee_TransportBillListDetail(string id)
        {
       
            string sql = @" SELECT transportbill.*,IFNULL(	vingdetail.nums,0) ReceivingNums,transportbill.MaterialId AS zhuangcheMaterialId FROM (SELECT T.* FROM (SELECT a.Id BillId,
 b.MaterialId,M.`Code`,M.`Name`,M.Spec,IFNULL(SUM(b.PackNums), 0) PackNums FROM pb_transportbill AS a LEFT JOIN pb_transportbilldetail AS b ON b.ParentId = a.Id LEFT JOIN PB_Material AS M ON b.MaterialId = M.Id WHERE a.Id = '"+id+"' GROUP BY a.Id,b.MaterialId ) AS T ORDER BY T.CODE ) AS transportbill left JOIN(SELECT BillId, MaterialId, IFNULL(sum(Nums), 0) nums FROM pb_tranrecevingdetail GROUP BY BillId, MaterialId) AS vingdetail ON vingdetail.BillId = transportbill.BillId AND vingdetail.MaterialId = transportbill.MaterialId UNION ALL SELECT	transportbill2.BillId,	transportbill2.MaterialId,	transportbill2.`Code`,	transportbill2.`Name`,	transportbill2.Spec,		'0' AS PackNums ,	IFNULL( transportbill2.nums, 0 ) ReceivingNums,	zhuangche.MaterialId AS zhuangcheMaterialId FROM	(SELECT	T.* FROM	(SELECT	a.Id BillId,	b.MaterialId,	M.`Code`,	M.`Name`,	M.Spec,	IFNULL( SUM( b.nums ), 0 ) nums 	FROM	pb_transportbill AS a	JOIN pb_tranrecevingdetail AS b ON b.BillId = a.Id	JOIN PB_Material AS M ON b.MaterialId = M.Id 	WHERE	a.Id = '"+id+"' 	GROUP BY	a.Id,	b.MaterialId 	) AS T ORDER BY	T.CODE ) AS transportbill2 LEFT JOIN ( SELECT ParentId, MaterialId FROM pb_transportbilldetail GROUP BY ParentId, MaterialId ) AS zhuangche ON zhuangche.ParentId = transportbill2.BillId  AND transportbill2.MaterialId = zhuangche.MaterialId  WHERE zhuangche.MaterialId IS NULL ";
            var listData = await Db.GetListBySqlAsync<See_TransportBill>(sql);
            return listData;
        }
        public async Task<int> GetThreshold(int Threshold)
        {

            return Threshold;

        }



        #region 钉钉模块
        /// <summary>
        /// 钉钉收货扫描包信息依据装车单获取包信息
        /// </summary>
        /// <param name="PackQrCode"></param>
        /// <param name="BillId"></param>
        /// <returns></returns>
        public async Task<ReceivePackDto> GetReceivePackDataAsync(string PackQrCode, string BillId)
        {
            //获取包Id
            string packid = PackQrCode.Split(',')?[1].ToString();
            //获取装车单明细包信息
            string sqlMain = @"SELECT c.Id AS PackId,c.BoxName,c.Nums FROM PB_TransportBillDetail AS a LEFT JOIN PB_PackList AS c ON a.PackId = c.Id WHERE c.Id = '" + packid + "' and  a.ParentId='" + BillId + "'  GROUP BY 	c.Id,c.BoxName,	c.Nums";
            //装车包信息
            var transportbillpackdata = await Db.GetListBySqlAsync<ReceivePackDto>(sqlMain);
            if (transportbillpackdata.Count > 0)
            {
                Expression<Func<PB_PackMaterialCount, PB_Material, ReceivePackDetailDto>> select = (a, b) => new ReceivePackDetailDto
                {
                    PackId = a.PackId,
                    MaterialId = a.MaterialId,
                    MaterialName = b.Name,
                    MaterialCode = b.Code,
                    MaterialSpec = b.Spec,
                    ProductCode = b.ProductCode,
                    Nums = a.Nums
                };
                select = select.BuildExtendSelectExpre();
                var q = from a in Db.GetIQueryable<PB_PackMaterialCount>().AsExpandable()
                        join b in Db.GetIQueryable<PB_Material>() on a.MaterialId equals b.Id into ab
                        from b in ab.DefaultIfEmpty()
                        select @select.Invoke(a, b);
                //获取获取收货明细包明细
                List<ReceivePackDetailDto> ReceivePackDetail = await q.Where(x => x.PackId == packid).ToListAsync();

                //获取装车单的装车数量
                string unsql = @"select * from PB_TransportBillDetail where ParentId ='" + BillId + "'";
                List<PB_TransportBillDetail> UnLoadList = await Db.GetListBySqlAsync<PB_TransportBillDetail>(unsql);
                var unlist = UnLoadList.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId, Nums = x.Sum(i => i.PackNums) }).ToList();

                //获取已签收数量
                List<PB_TransportBillDetailList> TransportBillDetailList = await Db.GetIQueryable<PB_TransportBillDetailList>().Where(x => x.BillId == BillId && x.Status == 0).ToListAsync();
                var BillDetail = TransportBillDetailList.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId, Nums = x.Sum(i => i.ReceivingNums) }).ToList();

                foreach (var item in ReceivePackDetail)
                {
                    //装车总数量
                    var itemdata = unlist.Where(x => x.MaterialId == item.MaterialId).FirstOrDefault();
                    //签收总数量
                    var billdata = BillDetail.Where(x => x.MaterialId == item.MaterialId).FirstOrDefault();
                    if (itemdata != null)
                    {
                        item.QuantitynotNums = (itemdata.Nums - (billdata == null ? 0 : billdata.Nums));
                    }
                }
                //创建弹出消息
                ReceivePackDto ReceivePack = new ReceivePackDto();
                ReceivePack.PackId = transportbillpackdata.FirstOrDefault().PackId;
                ReceivePack.PackQrCode = h_Pack + "," + transportbillpackdata.FirstOrDefault().PackId;
                ReceivePack.BoxName = transportbillpackdata.FirstOrDefault().BoxName;
                ReceivePack.Nums = transportbillpackdata.FirstOrDefault().Nums;
                ReceivePack.ReceivePackDetail = ReceivePackDetail;
                return ReceivePack;
            }
            else
            {
                throw new BusException("请扫描装车单对应的包!");
            }
        }

        /// <summary>
        /// 钉钉扫描成品/扫描包获取成品/包信息
        /// </summary>
        /// <param name="BillId">派车单Id</param>
        /// <param name="JobQrCode">成品码/包码</param>
        /// <returns></returns>
        public async Task<TranBillAcceptancelDTO> GetAcceptanceMateral(string BillId, string JobQrCode)
        {
            //解析请求头
            var jobId = JobQrCode.Split(',')?[1].ToString();
            var RequestHeader = JobQrCode.Split(',')?[0].ToString();
            //判断请求头扫的是否成品14 包13
            if (RequestHeader == "14")
            {

                //获取成品信息
                PB_JobBookingQrCode jobdata = await Db.GetIQueryable<PB_JobBookingQrCode>().Where(x => x.Id == jobId).FirstOrDefaultAsync();

                if (jobdata == null)
                {
                    throw new BusException("请扫描正确的成品码!");
                }
                else
                {
                    //获取派车明细单个成品的物料 
                    var Material = await Db.GetIQueryable<PB_Material>().Where(m => m.Id == jobdata.MaterialId).FirstOrDefaultAsync();
                    List<PB_TransportBillDetail> UnLoadList = await Db.GetIQueryable<PB_TransportBillDetail>().Where(x => x.ParentId == BillId && x.MaterialId == jobdata.MaterialId && x.PackId == "").ToListAsync();
                    var materdata = UnLoadList.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId, Nums = x.Sum(i => i.PackNums) }).FirstOrDefault();
                    List<PB_TransportBillDetail> TransportBillDetail = await Db.GetIQueryable<PB_TransportBillDetail>().Where(x => x.ParentId == BillId && x.MaterialId == jobdata.MaterialId).ToListAsync();
                    //获取当前装车数量
                    var billjobdata = TransportBillDetail.Where(x => x.PackId == "").ToList();
                    //获取当前物料包外的物料汇总数量
                    var billjobmaterial = billjobdata.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId, Nums = x.Sum(i => i.PackNums), ReceiptQuantity = x.Sum(i => i.ReceiptQuantity) }).FirstOrDefault();
                    TranBillAcceptancelDTO tbdata = new TranBillAcceptancelDTO();
                    tbdata.MaterialId = Material.Id;
                    tbdata.Code = Material.Code;
                    tbdata.Name = Material.Name;
                    tbdata.Spec = Material.Spec;
                    tbdata.PackId = "";
                    tbdata.PackQrCode = "";
                    tbdata.Nums = billjobmaterial.Nums;
                    tbdata.RemainingQuantity = billjobmaterial.Nums - billjobmaterial.ReceiptQuantity;
                    if (tbdata.Nums == 0)
                    {
                        throw new BusException("请检查物料是否在包外或进行扫描包码操作");
                    }
                    return tbdata;
                }




            }
            return null;
        }
        #endregion
        #endregion



        #region 收货扫码生成收货记录
        /// <summary>
        /// 扫描撞车外的包码或成品码完成收货动作
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task UnloadPackDataAsync(BillDetailDTO data)
        {
            //定义收货记录集合
            List<pb_tranrecevingdetail> pb_tranrecevingdetailList = new List<pb_tranrecevingdetail>();
            //定义收货记录表id
            string rvingdetailId = IdHelper.GetId();
            //派车单id
            string billId = data.billqrcode.Split(',')?[1].ToString();
            string packmodel = data.packqrcode.Split(',')?[0].ToString();
            string materialId = string.Empty;
            string jobid = data.packqrcode.Split(',')?[1].ToString();
            string packid = string.Empty;
            Base_User userdata = await Db.GetIQueryable<Base_User>().Where(x => x.Id == _operator.UserId).FirstOrDefaultAsync();
            Base_LinkType linktypedata = await _opdept.GetLinkType("MaterialCode");
            #region 定义请求头
            if (linktypedata.Whether == true)
            {
                if (packmodel == "13")
                {
                    packid = data.packqrcode.Split(',')[1].ToString();
                }
                else if (packmodel == "14")
                {
                    jobid = data.packqrcode.Split(',')[1].ToString();
                }
                else if (packmodel == "04")
                {
                    var model = data.packqrcode.Split(',');
                    if (model.Length > 2)
                    {
                        if (model.Length < 4)
                        {
                            throw new BusException("请扫描正确的二维码信息");
                        }
                        else
                        {
                            materialId = model?[3].ToString();
                        }
                    }
                    else
                    {
                        materialId = model?[1].ToString();
                    }
                    //合并重复物料指向新的物料Id
                    PB_Material materdata = await Db.GetIQueryable<PB_Material>().Where(x => x.Id == materialId).FirstOrDefaultAsync();
                    if (!materdata.TransferId.IsNullOrEmpty())
                    {
                        materialId = materdata.TransferId;
                    }
                }

                else
                {
                    //获取请求头
                    packmodel = data.JobQrCode.Split(',')?[0].ToString();
                    //获取成品Id
                    jobid = data.JobQrCode.Split(',')?[1].ToString();
                    if (!data.packqrcode.IsNullOrEmpty())
                    {
                        packid = data.packqrcode.Split(',')?[1].ToString();
                    }
                }
            }
            #endregion
            if (packmodel == "13")
            {
                string packId = data.packqrcode.Split(',')?[1].ToString();
                PB_PackList packdata = await Db.GetIQueryable<PB_PackList>().Where(x => x.Id == packId).FirstOrDefaultAsync();
                if (packdata == null)
                {
                    throw new BusException("包码不存在!");
                }
                if (packdata.PackageType == 0)
                {
                   
                        //验证包码是否之前扫过
                        var pb_tranrecevingdetail = await Db.GetIQueryable<pb_tranrecevingdetail>().Where(m => m.PackId == packId && m.BillId == billId).FirstOrDefaultAsync();
                        if (pb_tranrecevingdetail != null)
                        {
                            throw new BusException("该包码已扫过！");
                        }
                        var materdata =await Db.GetIQueryable<PB_Material>().Where(m => m.Id == packdata.MaterialId).FirstOrDefaultAsync();
                        //插入收货扫描包码记录
                        pb_tranrecevingdetail pb_Tranrecevingdetail = new pb_tranrecevingdetail();
                        pb_Tranrecevingdetail.Id = rvingdetailId;
                        pb_Tranrecevingdetail.BillId = billId;
                        pb_Tranrecevingdetail.MaterialId = materdata.Id;
                        pb_Tranrecevingdetail.PackId = packId;
                        pb_Tranrecevingdetail.JobId = "";
                        pb_Tranrecevingdetail.QrCode = data.packqrcode;
                        pb_Tranrecevingdetail.ReceivingUserId = _operator.UserId;
                        pb_Tranrecevingdetail.ReceivingUserName = userdata.RealName;
                        pb_Tranrecevingdetail.ReceivingTime = DateTime.Now;
                        pb_Tranrecevingdetail.Nums = data.Nums;
                        pb_tranrecevingdetailList.Add(pb_Tranrecevingdetail);
                       

                  
                }
                else if (packdata.PackageType == 1)
                {
                    var materdata = await Db.GetIQueryable<PB_Material>().Where(m => m.Id == packdata.MaterialId).FirstOrDefaultAsync();
                    var pb_tranrecevingdetail = await Db.GetIQueryable<pb_tranrecevingdetail>().Where(m => m.PackId == packId && m.BillId == billId).FirstOrDefaultAsync();
                        if (pb_tranrecevingdetail != null)
                        {
                            throw new BusException("该包码已扫过！");
                        }
                        #region 反写装车单已收货数量

                        #endregion
                        //插入收货扫描包码记录
                        pb_tranrecevingdetail pb_Tranrecevingdetail = new pb_tranrecevingdetail();
                        pb_Tranrecevingdetail.Id = rvingdetailId;
                        pb_Tranrecevingdetail.BillId = billId;
                        pb_Tranrecevingdetail.MaterialId = materdata.Id;
                        pb_Tranrecevingdetail.PackId = packId;
                        pb_Tranrecevingdetail.JobId = "";
                        pb_Tranrecevingdetail.QrCode = data.packqrcode;
                        pb_Tranrecevingdetail.ReceivingUserId = _operator.UserId;
                        pb_Tranrecevingdetail.ReceivingUserName = userdata.RealName;
                        pb_Tranrecevingdetail.ReceivingTime = DateTime.Now;
                        pb_Tranrecevingdetail.Nums =data.Nums;
                        pb_tranrecevingdetailList.Add(pb_Tranrecevingdetail);

                    
                   
                }
                else
                {
                    throw new BusException("请扫描正确的包信息");
                }
            }
        
            else if (packmodel == "14")
            {
                if (linktypedata.Whether == true)
                {

                    if (linktypedata.Whether == true)
                    {

                        PB_JobBookingQrCode jobdata = await Db.GetIQueryable<PB_JobBookingQrCode>().Where(x => x.Id == jobid).FirstOrDefaultAsync();
                        //通过扫描其他成品码获取装车明细一条数据
                        var materdata = await Db.GetIQueryable<PB_Material>().Where(m => m.Id == jobdata.MaterialId).FirstOrDefaultAsync();
                        //成品吗验证
                        if (jobdata==null)
                        {
                            throw new BusException("请检查扫描或输入的码是否是单个成品码");
                        }
                        pb_tranrecevingdetail WhetherExistsNull = await Db.GetIQueryable<pb_tranrecevingdetail>().Where(m => m.BillId == billId && m.JobId == jobid).FirstOrDefaultAsync();
                        if (WhetherExistsNull != null)
                        {
                            throw new BusException("该成品码已扫过");
                        }
                            //插入收货记录表
                            pb_tranrecevingdetail pb_Tranrecevingdetail = new pb_tranrecevingdetail();
                            pb_Tranrecevingdetail.Id = rvingdetailId;
                            pb_Tranrecevingdetail.BillId = billId;
                            pb_Tranrecevingdetail.MaterialId = materdata.Id;
                            pb_Tranrecevingdetail.PackId = "";
                            pb_Tranrecevingdetail.JobId = jobdata.Id;
                            pb_Tranrecevingdetail.QrCode = jobdata.QrCode;
                            pb_Tranrecevingdetail.ReceivingUserId = _operator.UserId;
                            pb_Tranrecevingdetail.ReceivingUserName = userdata.RealName;
                            pb_Tranrecevingdetail.ReceivingTime = DateTime.Now;
                            pb_Tranrecevingdetail.Nums = 1;
                            pb_tranrecevingdetailList.Add(pb_Tranrecevingdetail);
                       
                    }
                    else
                    {
                        //扫描组装件的单个物料成品
                        if (packid.IsNullOrEmpty())
                        {
                            //查询成品物料信息
                            PB_JobBookingQrCode jobdata = await Db.GetIQueryable<PB_JobBookingQrCode>().Where(x => x.Id == jobid).FirstOrDefaultAsync();
                            if (jobdata == null)
                            {
                                throw new BusException("请检查成品信息是否正确");
                            }
                            var materdata = await Db.GetIQueryable<PB_Material>().Where(m => m.Id == jobdata.MaterialId).FirstOrDefaultAsync();

                            //插入收货记录表
                               pb_tranrecevingdetail pb_Tranrecevingdetail = new pb_tranrecevingdetail();
                                pb_Tranrecevingdetail.Id = rvingdetailId;
                                pb_Tranrecevingdetail.BillId = billId;
                                pb_Tranrecevingdetail.MaterialId = materdata.Id;
                                pb_Tranrecevingdetail.PackId = "";
                                pb_Tranrecevingdetail.JobId = jobdata.Id;
                                pb_Tranrecevingdetail.QrCode = jobdata.QrCode;
                                pb_Tranrecevingdetail.ReceivingUserId = _operator.UserId;
                                pb_Tranrecevingdetail.ReceivingUserName = userdata.RealName;
                                pb_Tranrecevingdetail.ReceivingTime = DateTime.Now;
                                pb_Tranrecevingdetail.Nums = 1;
                                pb_tranrecevingdetailList.Add(pb_Tranrecevingdetail);
                         }
                        else
                        {
                            //查询成品物料信息
                            PB_JobBookingQrCode jobdata = await Db.GetIQueryable<PB_JobBookingQrCode>().Where(x => x.Id == jobid).FirstOrDefaultAsync();
                            if (jobdata == null)
                            {
                                throw new BusException("请检查成品信息是否正确");
                            }
                            var materdata = await Db.GetIQueryable<PB_Material>().Where(m => m.Id == jobdata.MaterialId).FirstOrDefaultAsync();
                            //插入收货记录表
                            pb_tranrecevingdetail pb_Tranrecevingdetail = new pb_tranrecevingdetail();
                            pb_Tranrecevingdetail.Id = rvingdetailId;
                            pb_Tranrecevingdetail.BillId = billId;
                            pb_Tranrecevingdetail.MaterialId = materdata.Id;
                            pb_Tranrecevingdetail.PackId = "";
                            pb_Tranrecevingdetail.JobId = jobdata.Id;
                            pb_Tranrecevingdetail.QrCode = jobdata.QrCode;
                            pb_Tranrecevingdetail.ReceivingUserId = _operator.UserId;
                            pb_Tranrecevingdetail.ReceivingUserName = userdata.RealName;
                            pb_Tranrecevingdetail.ReceivingTime = DateTime.Now;
                            pb_Tranrecevingdetail.Nums = 1;
                            pb_tranrecevingdetailList.Add(pb_Tranrecevingdetail);

                        }
                    }
                }
             
                
            }
            else if (packmodel == "04")
            {
                string MaterialId = string.Empty;
                var model = data.packqrcode.Split(',');
                if (model.Length > 2)
                {
                    MaterialId = model?[3].ToString();
                }
                else
                {
                    MaterialId = model?[1].ToString();
                }

                List<PB_TransportBillDetail> pbdata = await Db.GetIQueryable<PB_TransportBillDetail>().Where(x => x.ParentId == billId && x.MaterialId == MaterialId && x.PackId == "").ToListAsync();
                if (pbdata.Count > 0)
                {
                    var pb_mater =await Db.GetIQueryable<PB_Material>().Where(m=>m.Id== MaterialId).FirstOrDefaultAsync();
                                    #region 反写装车单已收货数量

                                    #endregion
                                    pb_tranrecevingdetail pb_Tranrecevingdetail = new pb_tranrecevingdetail();
                                    pb_Tranrecevingdetail.Id = rvingdetailId;
                                    pb_Tranrecevingdetail.BillId = billId;
                                    pb_Tranrecevingdetail.MaterialId = MaterialId;
                                    pb_Tranrecevingdetail.PackId = "";
                                    pb_Tranrecevingdetail.JobId = "";
                                    pb_Tranrecevingdetail.QrCode = pb_mater.QrCode;
                                    pb_Tranrecevingdetail.ReceivingUserId = _operator.UserId;
                                    pb_Tranrecevingdetail.ReceivingUserName = userdata.RealName;
                                    pb_Tranrecevingdetail.ReceivingTime = DateTime.Now;
                                    pb_Tranrecevingdetail.Nums = data.Nums;
                                    pb_tranrecevingdetailList.Add(pb_Tranrecevingdetail);                  
                }
                else
                {
                    var pb_mater = await Db.GetIQueryable<PB_Material>().Where(m => m.Id == MaterialId).FirstOrDefaultAsync();
                    #region 反写装车单已收货数量

                    #endregion
                    pb_tranrecevingdetail pb_Tranrecevingdetail = new pb_tranrecevingdetail();
                    pb_Tranrecevingdetail.Id = rvingdetailId;
                    pb_Tranrecevingdetail.BillId = billId;
                    pb_Tranrecevingdetail.MaterialId = MaterialId;
                    pb_Tranrecevingdetail.PackId = "";
                    pb_Tranrecevingdetail.JobId = "";
                    pb_Tranrecevingdetail.QrCode = pb_mater.QrCode;
                    pb_Tranrecevingdetail.ReceivingUserId = _operator.UserId;
                    pb_Tranrecevingdetail.ReceivingUserName = userdata.RealName;
                    pb_Tranrecevingdetail.ReceivingTime = DateTime.Now;
                    pb_Tranrecevingdetail.Nums = data.Nums;
                    pb_tranrecevingdetailList.Add(pb_Tranrecevingdetail);
                }
            }
            await Db.InsertAsync<pb_tranrecevingdetail>(pb_tranrecevingdetailList);
        }

        #endregion
        #region 私有成员

        #endregion

        #region 备装异常

        /// <summary>
        /// 获取备装异常数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PageResult<PB_TransportBillDTO>> GetDataAbnormalListAsync(PageInput<BilldConditionDTO> input)
        {
            var search = input.Search;
            Expression<Func<PB_TransportBill, PB_Vehicle, PB_DeliveryNotice, Base_EnumItem, PB_TransportBillDTO>> select = (a, b, c, d) => new PB_TransportBillDTO { PlateNO = b.PlateNO, SupplierId = b.SupplierId, Abstract = c.Abstract, IssueDate = c.IssueDate, TransportType = d.Name };
            select = select.BuildExtendSelectExpre();
            var q = from a in GetIQueryable().AsExpandable()
                    join b in Db.GetIQueryable<PB_Vehicle>() on a.Vehicle equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    join c in Db.GetIQueryable<PB_DeliveryNotice>() on a.DeliveryNoticeId equals c.Id into ac
                    from c in ac.DefaultIfEmpty()
                    join d in Db.GetIQueryable<Base_EnumItem>() on a.BillType equals d.Code into ad
                    from d in ad.Where(u => u.EnumCode.Contains("TransportType")).DefaultIfEmpty()
                    select @select.Invoke(a, b, c, d);

            //筛选
            if (!search.Keyword.IsNullOrEmpty())
            {
                var keyword = $"%{search.Keyword}%";
                q = q.Where(x =>
                      EF.Functions.Like(x.Id, keyword)
                      || EF.Functions.Like(x.DeliveryNoticeId, keyword)
                      || EF.Functions.Like(x.PlateNO, keyword));
            }
            if (!search.BillType.IsNullOrEmpty())
            {
                q = q.Where(x => x.BillType == search.BillType);
            }
            //查询装车明细有异常的
            List<PB_TransportBillDetail> TransportBillDetail = await Db.GetIQueryable<PB_TransportBillDetail>().Where(x => x.TrueOrFalse == false && x.IsHandle == false).ToListAsync();
            var billdata = TransportBillDetail.GroupBy(x => new { x.ParentId }).Select(x => new { ParentId = x.Key.ParentId }).ToList();
            List<string> ids = new List<string>();
            foreach (var item in billdata)
            {
                ids.Add(item.ParentId);
            }
            q = q.Where(x => ids.Contains(x.Id));
            q = q.Where(x => x.State >= 4);
            //q = q.Where(m => _operator.Property.DeptIds.Contains(m.DeptId));
            return await q.GetPageResultAsync(input);
        }

        /// <summary>
        /// 获取装车异常的明细
        /// </summary>
        /// <param name="BillId">派车单Id</param>
        /// <returns></returns>
        public async Task<List<TransportBillDetailAbnormal>> GetTransportBillDetailAbnormalListAsync(string BillId)
        {
            string sql = @"select *,ROW_NUMBER() over(order by MaterialId) as RowId from (
-- 单件物料
select a.Id,a.PackId,a.JobId,a.MaterialId,b.`Name` as BoxName,b.`Code` as MaterialCode,b.Spec as MaterialSpec,a.PackNums,a.TrueOrFalse,a.IsHandle,'0' as StockStatus,'1' as Type from pb_transportbilldetail as a 
left join pb_material as b on a.MaterialId=b.Id
where a.ParentId='{0}' and  a.TrueOrFalse=0 and PackId='' and JobId=''
UNION ALL
-- 包
select a.Id,a.PackId,a.JobId,a.MaterialId,b.BoxName,c.`Code` as MaterialCode,c.Spec as MaterialSpec,a.PackNums,a.TrueOrFalse,a.IsHandle,case when b.`Status`=4 then '1' else '0' end as StockStatus,'3' as Type from pb_transportbilldetail as a 
left join pb_packlist as b on a.PackId=b.Id 
left join pb_material as c on a.MaterialId=c.Id
where a.ParentId='{0}' and  a.TrueOrFalse=0 and PackId!='' 
UNION ALL
-- 单个成品
select a.Id,a.PackId,a.JobId,a.MaterialId,b.`Name` as BoxName,b.`Code` as MaterialCode,b.Spec as MaterialSpec,a.PackNums,a.TrueOrFalse,a.IsHandle,case when IFNULL(c.JobId,'')!='' then '1' else '0' end as StockStatus,'2' as Type  from pb_transportbilldetail as a 
left join pb_material as b on a.MaterialId=b.Id
left join pb_unloadlist as c on a.JobId=c.JobId
where a.ParentId='{0}' and  a.TrueOrFalse=0 and a.JobId!=''
) as t ";
            string sqlMain = string.Format(sql, BillId);
            return await Db.GetListBySqlAsync<TransportBillDetailAbnormal>(sqlMain);

        }

        /// <summary>
        /// 异常处理(生成出库单据)
        /// </summary>
        /// <param name="BillId">派车单Id</param>
        /// <returns></returns>
        public async Task ExceptionHandlingAsync(string BillId)
        {
            //获取装车的异常数据
            string sql = @"select *,ROW_NUMBER() over(order by MaterialId) as RowId from (
-- 单件物料
select a.Id,a.PackId,a.JobId,a.MaterialId,b.`Name` as BoxName,b.`Code` as MaterialCode,b.Spec as MaterialSpec,a.PackNums,a.TrueOrFalse,a.IsHandle,'0' as StockStatus,'1' as Type from pb_transportbilldetail as a 
left join pb_material as b on a.MaterialId=b.Id
where a.ParentId='{0}' and  a.TrueOrFalse=0 and PackId='' and JobId=''
UNION ALL
-- 包
select a.Id,a.PackId,a.JobId,a.MaterialId,b.BoxName,c.`Code` as MaterialCode,c.Spec as MaterialSpec,a.PackNums,a.TrueOrFalse,a.IsHandle,case when b.`Status`=4 then '1' else '0' end as StockStatus,'3' as Type from pb_transportbilldetail as a 
left join pb_packlist as b on a.PackId=b.Id 
left join pb_material as c on a.MaterialId=c.Id
where a.ParentId='{0}' and  a.TrueOrFalse=0 and PackId!='' 
UNION ALL
-- 单个成品
select a.Id,a.PackId,a.JobId,a.MaterialId,b.`Name` as BoxName,b.`Code` as MaterialCode,b.Spec as MaterialSpec,a.PackNums,a.TrueOrFalse,a.IsHandle,case when IFNULL(c.JobId,'')!='' then '1' else '0' end as StockStatus,'2' as Type  from pb_transportbilldetail as a 
left join pb_material as b on a.MaterialId=b.Id
left join pb_unloadlist as c on a.JobId=c.JobId
where a.ParentId='{0}' and  a.TrueOrFalse=0 and a.JobId!=''
) as t ";
            string sqlMain = string.Format(sql, BillId);

            List<TransportBillDetailAbnormal> listdata= await Db.GetListBySqlAsync<TransportBillDetailAbnormal>(sqlMain);

            string UpSql = string.Empty;
            foreach (var item in listdata)
            {
                //处理装车异常明细改为已处理
                UpSql += @" update pb_transportbilldetail set TrueOrFalse=1 where Id='" + item.Id + "'; ";
            }

            Base_User userdata = await Db.GetIQueryable<Base_User>().Where(x => x.Id == _operator.UserId).FirstOrDefaultAsync();

            List<TD_OutStorage> OutStorageList = new List<TD_OutStorage>();
            List<TD_OutStorDetail> OutStorDetailList = new List<TD_OutStorDetail>();
            List<TD_OutStorRecord> OutStorRecordList = new List<TD_OutStorRecord>();
            List<PB_StockLog> StockLogList = new List<PB_StockLog>();

            string outId = IdHelper.GetId();

            //单件物料
            var djmaterialdata = listdata.Where(x => x.Type == "1" && x.StockStatus == "0").ToList();
            List<string> materialids = new List<string>();
            foreach (var item in djmaterialdata)
            {
                materialids.Add(item.MaterialId);
            }
            List<IT_LocalDetail> materialdetail = await Db.GetIQueryable<IT_LocalDetail>().Where(x => materialids.Contains(x.MaterialId)).ToListAsync();
            
            foreach (var item in djmaterialdata)
            {
                var itemdata = materialdetail.Where(x => x.MaterialId == item.MaterialId).ToList();
                if (!itemdata.IsNullOrEmpty())
                {
                    Double? dnums = item.PackNums;
                    foreach (var mitem in itemdata)
                    {
                        if (dnums > 0)
                        {
                            if (mitem.Num <= dnums)
                            {
                                UpSql += @" delete from IT_LocalDetail where Id='" + mitem.Id + "'; ";
                                if (mitem.OldOrNew == 0)
                                {
                                    UpSql += @" update IT_LocalMaterial set Nums_O=IFNULL(Nums_O,0)-" + mitem.Num + ",ScanNum=IFNULL(ScanNum,0)-" + mitem.Num + " where LocalId='" + mitem.LocalId + "' and MaterialId='" + mitem.MaterialId + "';";
                                }
                                else if (mitem.OldOrNew == 1)
                                {
                                    UpSql += @" update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)-" + mitem.Num + ",ScanNum=IFNULL(ScanNum,0)-" + mitem.Num + " where LocalId='" + mitem.LocalId + "' and MaterialId='" + mitem.MaterialId + "';";
                                }
                                
                                PB_StockLog StockLog = new PB_StockLog();
                                StockLog.Id = IdHelper.GetId();
                                StockLog.PackId = "";
                                StockLog.MaterialId = item.MaterialId;
                                StockLog.StorId = mitem.StorId;
                                StockLog.LocationId = mitem.LocalId;
                                StockLog.StockNumber = mitem.Num;
                                StockLog.CreatorId = _operator.UserId;
                                StockLog.CreatorName = userdata.RealName;
                                StockLog.OperatorId = _operator.UserId;
                                StockLog.Type = 1;
                                StockLog.OrderID = BillId;
                                StockLog.CreateTime = DateTime.Now;
                                StockLog.State = 1;
                                StockLog.OldOrNew = mitem.OldOrNew;
                                StockLog.CirBillId = "";
                                StockLog.JobId = "";
                                StockLogList.Add(StockLog);

                                TD_OutStorDetail OutStorDetail = new TD_OutStorDetail();
                                OutStorDetail.Id = IdHelper.GetId();
                                OutStorDetail.StorId = mitem.StorId;
                                OutStorDetail.OutStorId = outId;
                                OutStorDetail.LocalId = mitem.LocalId;
                                OutStorDetail.BarCode = h_Material + "," + item.MaterialId;
                                OutStorDetail.MaterialId = item.MaterialId;
                                OutStorDetail.Price = Convert.ToDouble(mitem.Price);
                                OutStorDetail.TotalAmt = Convert.ToDouble(mitem.Price * mitem.Num);
                                OutStorDetail.OutNum = Convert.ToDouble(mitem.Num);
                                OutStorDetail.CreateTime = DateTime.Now;
                                OutStorDetail.CreatorId = _operator.UserId;
                                OutStorDetail.Deleted = false;
                                OutStorDetail.OldOrNew = mitem.OldOrNew;
                                OutStorDetailList.Add(OutStorDetail);
                                dnums -= mitem.Num;
                            }
                            else
                            {
                                UpSql += @" update IT_LocalDetail set Num=IFNULL(Num,0)-" + dnums + " where Id='" + mitem.Id + "'; ";
                                if (mitem.OldOrNew == 0)
                                {
                                    UpSql += @" update IT_LocalMaterial set Nums_O=IFNULL(Nums_O,0)-" + dnums + ",ScanNum=IFNULL(ScanNum,0)-" + dnums + " where LocalId='" + mitem.LocalId + "' and MaterialId='" + mitem.MaterialId + "';";
                                }
                                else if (mitem.OldOrNew == 1)
                                {
                                    UpSql += @" update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)-" + dnums + ",ScanNum=IFNULL(ScanNum,0)-" + dnums + " where LocalId='" + mitem.LocalId + "' and MaterialId='" + mitem.MaterialId + "';";
                                }
                                
                                PB_StockLog StockLog = new PB_StockLog();
                                StockLog.Id = IdHelper.GetId();
                                StockLog.PackId = "";
                                StockLog.MaterialId = item.MaterialId;
                                StockLog.StorId = mitem.StorId;
                                StockLog.LocationId = mitem.LocalId;
                                StockLog.StockNumber = dnums;
                                StockLog.CreatorId = _operator.UserId;
                                StockLog.CreatorName = userdata.RealName;
                                StockLog.OperatorId = _operator.UserId;
                                StockLog.Type = 1;
                                StockLog.OrderID = BillId;
                                StockLog.CreateTime = DateTime.Now;
                                StockLog.State = 1;
                                StockLog.OldOrNew = mitem.OldOrNew;
                                StockLog.CirBillId = "";
                                StockLog.JobId = "";
                                StockLogList.Add(StockLog);

                                TD_OutStorDetail OutStorDetail = new TD_OutStorDetail();
                                OutStorDetail.Id = IdHelper.GetId();
                                OutStorDetail.StorId = mitem.StorId;
                                OutStorDetail.OutStorId = outId;
                                OutStorDetail.LocalId = mitem.LocalId;
                                OutStorDetail.BarCode = h_Material + "," + item.MaterialId;
                                OutStorDetail.MaterialId = item.MaterialId;
                                OutStorDetail.Price = Convert.ToDouble(mitem.Price);
                                OutStorDetail.TotalAmt = Convert.ToDouble(mitem.Price * dnums);
                                OutStorDetail.OutNum = Convert.ToDouble(dnums);
                                OutStorDetail.CreateTime = DateTime.Now;
                                OutStorDetail.CreatorId = _operator.UserId;
                                OutStorDetail.Deleted = false;
                                OutStorDetail.OldOrNew = mitem.OldOrNew;
                                OutStorDetailList.Add(OutStorDetail);
                                dnums -= dnums;
                            }
                        }
                        else
                        {
                            continue;
                        }
                    }
                }
                
            }

            //单个成品
            var jobdata = listdata.Where(x => x.Type == "2" && x.StockStatus == "0").ToList();
            List<string> jobids = new List<string>();
            foreach (var item in jobdata)
            {
                jobids.Add(item.JobId);
            }
            List<IT_LocalDetail> jobdetail = await Db.GetIQueryable<IT_LocalDetail>().Where(x => jobids.Contains(x.JobId)).ToListAsync();
            foreach (var item in jobdetail)
            {
                UpSql += @" delete from IT_LocalDetail where Id='" + item.Id + "'; ";
                if (item.OldOrNew == 0)
                {
                    UpSql += @" update IT_LocalMaterial set Nums_O=IFNULL(Nums_O,0)-" + item.Num + ",ScanNum=IFNULL(ScanNum,0)-" + item.Num + " where LocalId='" + item.LocalId + "' and MaterialId='" + item.MaterialId + "';";
                }
                else if (item.OldOrNew == 1)
                {
                    UpSql += @" update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)-" + item.Num + ",ScanNum=IFNULL(ScanNum,0)-" + item.Num + " where LocalId='" + item.LocalId + "' and MaterialId='" + item.MaterialId + "';";
                }
                PB_StockLog StockLog = new PB_StockLog();
                StockLog.Id = IdHelper.GetId();
                StockLog.PackId = "";
                StockLog.MaterialId = item.MaterialId;
                StockLog.StorId = item.StorId;
                StockLog.LocationId = item.LocalId;
                StockLog.StockNumber = item.Num;
                StockLog.CreatorId = _operator.UserId;
                StockLog.CreatorName = userdata.RealName;
                StockLog.OperatorId = _operator.UserId;
                StockLog.Type = 1;
                StockLog.OrderID = BillId;
                StockLog.CreateTime = DateTime.Now;
                StockLog.State = 1;
                StockLog.OldOrNew = item.OldOrNew;
                StockLog.CirBillId = "";
                StockLog.JobId = item.JobId;
                StockLogList.Add(StockLog);

                TD_OutStorDetail OutStorDetail = new TD_OutStorDetail();
                OutStorDetail.Id = IdHelper.GetId();
                OutStorDetail.StorId = item.StorId;
                OutStorDetail.OutStorId = outId;
                OutStorDetail.LocalId = item.LocalId;
                OutStorDetail.BarCode = h_FinishedProduct + "," + item.JobId;
                OutStorDetail.MaterialId = item.MaterialId;
                OutStorDetail.Price = Convert.ToDouble(item.Price);
                OutStorDetail.TotalAmt = Convert.ToDouble(item.Price * item.Num);
                OutStorDetail.OutNum = Convert.ToDouble(item.Num);
                OutStorDetail.CreateTime = DateTime.Now;
                OutStorDetail.CreatorId = _operator.UserId;
                OutStorDetail.Deleted = false;
                OutStorDetail.OldOrNew = item.OldOrNew;
                OutStorDetailList.Add(OutStorDetail);
            }

            //包
            var packdata = listdata.Where(x => x.Type == "3" && x.StockStatus == "0").ToList();
            var packlist = packdata.GroupBy(x => new { x.PackId }).Select(x => new { PackId = x.Key.PackId }).ToList();
            List<string> packIds = new List<string>();
            foreach (var item in packlist)
            {
                packIds.Add(item.PackId);
            }
            List<IT_LocalDetail> packdetail = await Db.GetIQueryable<IT_LocalDetail>().Where(x => packIds.Contains(x.PackId)).ToListAsync();
            foreach (var item in packdetail)
            {
                UpSql += @" delete from IT_LocalDetail where Id='" + item.Id + "'; ";
                if (item.OldOrNew == 0)
                {
                    UpSql += @" update IT_LocalMaterial set Nums_O=IFNULL(Nums_O,0)-" + item.Num + ",ScanNum=IFNULL(ScanNum,0)-" + item.Num + " where LocalId='" + item.LocalId + "' and MaterialId='" + item.MaterialId + "';";
                }
                else if (item.OldOrNew == 1)
                {
                    UpSql += @" update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)-" + item.Num + ",ScanNum=IFNULL(ScanNum,0)-" + item.Num + " where LocalId='" + item.LocalId + "' and MaterialId='" + item.MaterialId + "';";
                }
                UpSql += @" update PB_PackList set Status=4,OutStorTime=NOW(),OutStorUserId='" + _operator.UserId + "',OutStorUserName='" + userdata.RealName + "' where Id='" + item.PackId + "'; ";
                PB_StockLog StockLog = new PB_StockLog();
                StockLog.Id = IdHelper.GetId();
                StockLog.PackId = item.PackId;
                StockLog.MaterialId = item.MaterialId;
                StockLog.StorId = item.StorId;
                StockLog.LocationId = item.LocalId;
                StockLog.StockNumber = item.Num;
                StockLog.CreatorId = _operator.UserId;
                StockLog.CreatorName = userdata.RealName;
                StockLog.OperatorId = _operator.UserId;
                StockLog.Type = 1;
                StockLog.OrderID = BillId;
                StockLog.CreateTime = DateTime.Now;
                StockLog.State = 1;
                StockLog.OldOrNew = item.OldOrNew;
                StockLog.CirBillId = "";
                StockLog.JobId = "";
                StockLogList.Add(StockLog);

                TD_OutStorDetail OutStorDetail = new TD_OutStorDetail();
                OutStorDetail.Id = IdHelper.GetId();
                OutStorDetail.StorId = item.StorId;
                OutStorDetail.OutStorId = outId;
                OutStorDetail.LocalId = item.LocalId;
                OutStorDetail.BarCode = h_Pack + "," + item.PackId;
                OutStorDetail.MaterialId = item.MaterialId;
                OutStorDetail.Price = Convert.ToDouble(item.Price);
                OutStorDetail.TotalAmt = Convert.ToDouble(item.Price * item.Num);
                OutStorDetail.OutNum = Convert.ToDouble(item.Num);
                OutStorDetail.CreateTime = DateTime.Now;
                OutStorDetail.CreatorId = _operator.UserId;
                OutStorDetail.Deleted = false;
                OutStorDetail.OldOrNew = item.OldOrNew;
                OutStorDetailList.Add(OutStorDetail);
            }

            var outrecord = OutStorDetailList.GroupBy(x => new { x.StorId, x.MaterialId, x.Price }).Select(x => new { StorId = x.Key.StorId, MaterialId = x.Key.MaterialId, Price = x.Key.Price, Nums = x.Sum(i => i.OutNum) }).ToList();
            Double? outsumnums = 0;
            Double? outTotalAmt = 0;
            foreach (var item in outrecord)
            {
                TD_OutStorRecord OutStorRecord = new TD_OutStorRecord();
                OutStorRecord.Id = IdHelper.GetId();
                OutStorRecord.StorId = item.StorId;
                OutStorRecord.OutStorId = outId;
                OutStorRecord.MaterialId = item.MaterialId;
                OutStorRecord.Price = item.Price;
                OutStorRecord.TotalAmt = item.Price * item.Nums;
                OutStorRecord.OutNum = item.Nums;
                OutStorRecord.CreateTime = DateTime.Now;
                OutStorRecord.CreatorId = _operator.UserId;
                OutStorRecord.Deleted = false;
                OutStorRecordList.Add(OutStorRecord);
                outsumnums += item.Nums;
                outTotalAmt += item.Price * item.Nums;
            }

            TD_OutStorage OutStorage = new TD_OutStorage();
            OutStorage.Id = outId;
            OutStorage.StorageId = outrecord.FirstOrDefault().StorId;
            OutStorage.Code = GetTimeStamp();
            OutStorage.OutTime = DateTime.Now;
            OutStorage.OutType = "OtherOut";
            OutStorage.RefCode = BillId;
            OutStorage.OutNum = outsumnums;
            OutStorage.TotalAmt = outTotalAmt;
            OutStorage.Status = 0;
            OutStorage.Remarks = "备装异常出库";
            OutStorage.CreateTime = DateTime.Now;
            OutStorage.CreatorId = _operator.UserId;
            OutStorage.Deleted = false;
            OutStorage.QrCode = h_OutStorage + "," + outId;
            OutStorage.DepId = userdata.DepartmentId;
            OutStorage.ProjectId = "";
            OutStorage.DesignId = "";
            OutStorage.FactoryId = userdata.FactoryId;
            OutStorageList.Add(OutStorage);

            await Db.ExecuteSqlAsync(UpSql);

            await Db.InsertAsync<PB_StockLog>(StockLogList);
            await Db.InsertAsync<TD_OutStorDetail>(OutStorDetailList);
            await Db.InsertAsync<TD_OutStorRecord>(OutStorRecordList);
            await Db.InsertAsync<TD_OutStorage>(OutStorageList);

        }


        #endregion

    }
}